R 将值赋给从旧变量获得的新变量

R 将值赋给从旧变量获得的新变量,r,dplyr,sum,R,Dplyr,Sum,我想给从旧变量中获得的新变量指定一个特定值。在我的例子中,我有这个数据表 $ date : Date, format: "2018-01-05" "2018-01-06" "2018-01-07" ... $ price : num 100 110 120 ... $ Sentiment: int -2 3 0 ... 我想添加名为“tot_情绪”的新变量,如果情绪变量的值为负值,则指定“负值”,如果情绪变量的值为正值,则指定“正值”,如果情绪变量的值为零,则指定“中性

我想给从旧变量中获得的新变量指定一个特定值。在我的例子中,我有这个数据表

 $ date     : Date, format: "2018-01-05" "2018-01-06" "2018-01-07" ...
 $ price    : num  100 110 120 ...
 $ Sentiment: int  -2 3 0 ...
我想添加名为“tot_情绪”的新变量,如果情绪变量的值为负值,则指定“负值”,如果情绪变量的值为正值,则指定“正值”,如果情绪变量的值为零,则指定“中性”

预期产出:

 $ date     : Date, format: "2018-01-05" "2018-01-06" "2018-01-07" ...
 $ price    : num  100 110 120 ...
 $ Sentiment: int  -2 3 0 ...
 $ tot_sentiment: char  negative positive neutral ...
我尝试了以下代码:

new_dt<- dt %>% mutate(tot_sentiment = sum(Sentiment)....blablabla.....)
new_dt%变异(tot_情绪=sum(情绪)

这可以使用
ifelse
case\u在
dplyr
中执行。但是,您可以直接使用
符号
并对值进行子集

df$tot_sentiment <- c("negative", "neutral", "positive")[sign(df$b) + 2]

df
#  a  b tot_sentiment
#1 a -2      negative
#2 b  0       neutral
#3 c  1      positive
#4 d  2      positive
#5 e -5      negative

df$tot\u情绪这可以使用
ifelse
case\u在
dplyr
中执行。但是,您可以直接使用
符号
并对值进行子集

df$tot_sentiment <- c("negative", "neutral", "positive")[sign(df$b) + 2]

df
#  a  b tot_sentiment
#1 a -2      negative
#2 b  0       neutral
#3 c  1      positive
#4 d  2      positive
#5 e -5      negative

df$tot_情绪我们可以使用
factor
更改
符号
ed列上的级别

df$tot_sentiment <-  factor(sign(df$b), levels = -1:1, 
       labels = c("negative", "neutral", "positive"))
df
#  a  b tot_sentiment
#1 a -2      negative
#2 b  0       neutral
#3 c  1      positive
#4 d  2      positive
#5 e -5      negative

df$tot_情绪我们可以使用
factor
更改
符号
ed列上的级别

df$tot_sentiment <-  factor(sign(df$b), levels = -1:1, 
       labels = c("negative", "neutral", "positive"))
df
#  a  b tot_sentiment
#1 a -2      negative
#2 b  0       neutral
#3 c  1      positive
#4 d  2      positive
#5 e -5      negative
df$tot\u