向r中的列单元格追加文本字符串



假设我在R中有这样一个简单的数据框架:

Col1 <- 1:10
Col2 <- 15:6
df <- data.frame(Col1, Col2)

现在我想在新列中添加一个文本字符串,该字符串表示这两列中每列中的数字。

df$Eval = "Evaluation:"

Col1中的数字为>5时,我想在向现有字符串"Evaluation:"追加文本字符串" Col1) This number is high."。当Col1中的数字为<5时,我想添加" Col1) This number is low."代替。同样,我想在Col2中添加一个关于数字的文本字符串。

示意图:

df[df$Col1 >5,]$Eval = " Col1) This number is high."
df[df$Col1 <5,]$Eval = " Col1) This number is low."
df[df$Col2 >9,]$Eval = " Col2) This number is high."
df[df$Col2 <9,]$Eval = " Col2) This number is low."

最后,列Eval中的第一个单元格应该最终具有文本字符串Evaluation: Col1) This number is low. Col2) This number is high.

我怎样才能做到这一点?我试过使用paste(),但是没有用。

你差一点就成功了。您确实可以使用paste作为:

Col1 <- 1:10
Col2 <- 15:6
df <- data.frame(Col1, Col2)
# create a new column evaluation
df$Eval = "Evaluation:"
# select the right rows
select <- df$Col1 > 5
# create and allocate your new variable to Eval
df$Eval[select] = paste(df$Eval[select], " Col1) This number is high.")

您可以为所有特定选择复制此代码。

希望对您有所帮助:

df <- df %>% mutate( ev_1 = case_when 
(Col1 <5 ~ paste("Evaluauation: Col1) This Number is Low."),
Col1 >5 ~ ("Evaluauation: Col1) This Number is High.")),
ev_2 = case_when
(Col2 <9 ~ paste("Col2) This number is Low."),
Col2>9 ~ paste("Col2) This number is High.")),
Evaluation = paste(ev_1 , ev_2)) %>%
select(-ev_1, -ev_2)
df  

Col1 Col2                                                          Evaluation
1     1   15  Evaluauation: Col1) This Number is Low. Col2) This number is High.
2     2   14  Evaluauation: Col1) This Number is Low. Col2) This number is High.
3     3   13  Evaluauation: Col1) This Number is Low. Col2) This number is High.
4     4   12  Evaluauation: Col1) This Number is Low. Col2) This number is High.
5     5   11                                       NA Col2) This number is High.
6     6   10 Evaluauation: Col1) This Number is High. Col2) This number is High.
7     7    9                         Evaluauation: Col1) This Number is High. NA
8     8    8  Evaluauation: Col1) This Number is High. Col2) This number is Low.
9     9    7  Evaluauation: Col1) This Number is High. Col2) This number is Low.
10   10    6  Evaluauation: Col1) This Number is High. Col2) This number is Low

最新更新