假設我在 R 中有一個像這樣的簡單資料框:
Col1 <- 1:10
Col2 <- 15:6
df <- data.frame(Col1, Col2)
現在我想在一個新列中添加一個文本字串,說明這兩列中每一列的數字。
df$Eval = "Evaluation:"
當 in 的數字Col1
大于 5 時,我想將一個文本字串附加" Col1) This number is high."
到現有的 string "Evaluation:"
。當數字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()
,但無濟于事。
uj5u.com熱心網友回復:
你快到了。您確實可以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.")
您可以為所有特定選擇復制此代碼。
uj5u.com熱心網友回復:
希望這可以幫助:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491341.html
下一篇:根據另一個R檢查一列的值