我有df1,我想设置另一列的名称更接近0:
x= c(1, 3,2)
y=c(2, 1,4)
df1 = data. frame(x, y)
x y
1 2
3 1
2 4
I want to get this:
x y closer
1 2 x
3 1 y
2 4 x
使用max.col
,我们可以获得最接近0的值的索引
max.col(-abs(df))
#[1] 1 2 1
要获取列名,我们可以使用此索引从数据帧的names
中将其作为子集
df$closest <- names(df)[max.col(-abs(df))]
df
# x y closest
#1 1 4 x
#2 5 2 y
#3 3 6 x
数据
df <- structure(list(x = c(1L, 5L, 3L), y = c(4L, 2L, 6L)), class = "data.frame",
row.names = c(NA, -3L))
另一个选择是:
df$closest <- colnames(df)[apply(df, 1, which.min)]
使用以下df
:
structure(list(x = c(1L, 5L, 3L), y = c(4L, 2L, 6L)), class = "data.frame", row.names = c(NA,
-3L)) -> df