我有一个数据框,其一部分如下所示:
library(data.table)
df <- fread(
"round1 round2 round3 round4 round5 round6 a
8 12 18 32 40 36 32
6 12 18 24 30 36 30
8 16 18 24 30 36 18
4 12 12 24 30 36 24
6 16 24 32 40 48 24
8 12 18 24 30 36 30
8 12 18 24 30 36 18
8 16 24 32 40 48 40
8 16 24 24 30 48 48",
header = TRUE
)
我想创建一个名为x
的列,该列将简单地选择等于a
中条目的整数。我尝试遵循,但是语法不正确。
for (i in df$a){
if (df$a[i] = df$round2[i]){
df$x[i] = 1
} ifelse (df$a[i] = df$round3[i]){
df$x[i] = 2
} ifelse (df$a[i] = df$round4[i]){
df$x[i] = 3
} ifelse (df$a[i] = df$round5[i]){
df$x[i] = 4
} ifelse (df$a[i] = df$round6[i]){
df$x[i] = 5
} ifelse (df$a[i] = df$round7[i]){
df$x[i] = 6
}
}
所需的输出:
library(data.table)
df2 <- fread(
"round2 round3 round4 round5 round6 round7 a x
8 12 18 32 40 36 32 4
6 12 18 24 30 36 30 5
8 16 18 24 30 36 18 3
4 12 12 24 30 36 24 4
6 16 24 32 40 48 24 3
8 12 18 24 30 36 30 5
8 12 18 24 30 36 18 3
8 16 24 32 40 48 40 5
8 16 24 24 30 48 48 6",
header = TRUE
)
答案 0 :(得分:1)
将df
与a
的值进行比较,然后通过将max.col
指定为ties.method
来使用"first"
max.col(df == df$a, ties.method = "first")
#[1] 4 5 3 4 3 5 3 5 6