您好,我有一個資料框,其中第 2 列和第 3 列有整數
head(mtcars)[,c(5,6)]
|drat |wt|
| ---|---|
|3.90|2.620|
|3.90|2.875|
|3.85|2.320|
|3.08|3.215|
|3.15|3.440|
|2.76|3.460|
問題是我想以逐行方式添加第三列,如果 col2 數字大于 col3 數字,那么同一行上的值將是“-”。如果相反(col2 大于 col3),那么新列上的行值將是“ ”。
這是我嘗試過的:
mtcars %>%
rowwise() %>%
mutate(strand =
if (drat < wt ){
print("-"); else
print(" ")
})
但我收到錯誤訊息:
錯誤:“}”中出現意外的“}”
預期輸出:
|drat|wt|strand|
|----|--|------|
|3.90|2.620|"-"|
|3.90|2.875|"-"|
|3.85|2.320|"-"|
|3.08|3.215|" "|
|3.15|3.440|" "|
|2.76|3.460|" "|
uj5u.com熱心網友回復:
你不需要{}and ;:
head(mtcars)[,c(5,6)] %>%
rowwise() %>%
mutate(strand = if (drat < wt )print("-") else print(" "))
drat wt strand
<dbl> <dbl> <chr>
1 3.9 2.62
2 3.9 2.88
3 3.85 2.32
4 3.08 3.22 -
5 3.15 3.44 -
6 2.76 3.46 -
uj5u.com熱心網友回復:
替換分號“;” 和 ”}”。否則打開一個新的“{”這是你的代碼,它運行良好:
mtcars %>%
rowwise() %>%
mutate(strand =
if (drat < wt ){
print("-")} else{
print(" ")
})
uj5u.com熱心網友回復:
使用 ifelse 可能是最簡單的:
mtcars$strand <- ifelse(test = mtcars$drat < mtcars$wt,
yes = " ",
no = "-")
mpg cyl disp hp drat wt qsec vs am gear carb strand
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 -
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 -
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 -
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
uj5u.com熱心網友回復:
我認為這適合你:
mtcars %>%
mutate(strand = ifelse (drat < wt, '-', ' '))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/487586.html
