英文:
How to get the column name of the one which value is closest to 0?
问题
Sure, here is the translated code and desired output:
我有数据框**df1**,我想设置另一列,其名称是值最接近0的列:
**df1**
```r
x <- c(1, 3,2)
y <- c(2, 1,4)
df1 <- data. frame(x, y)
df1
# x y
#1 1 2
#2 3 1
#3 2 4
期望输出:
# x y closer
#1 1 2 x
#2 3 1 y
#3 2 4 x
英文:
I have the data frame df1 and I want to set another column with the name of the column that its value is closer to 0:
df1
x <- c(1, 3,2)
y <- c(2, 1,4)
df1 <- data. frame(x, y)
df1
# x y
#1 1 2
#2 3 1
#3 2 4
The desire output:
# x y closer
#1 1 2 x
#2 3 1 y
#3 2 4 x
</details>
# 答案1
**得分**: 2
Using `max.col`,我们可以得到距离0最近的值的索引
```R
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))
英文:
Using max.col
we can get the index of value which is closest to 0
max.col(-abs(df))
#[1] 1 2 1
to get column names we can use this index to subset it from names
of the dataframe
df$closest <- names(df)[max.col(-abs(df))]
df
# x y closest
#1 1 4 x
#2 5 2 y
#3 3 6 x
data
df <- structure(list(x = c(1L, 5L, 3L), y = c(4L, 2L, 6L)), class = "data.frame",
row.names = c(NA, -3L))
答案2
得分: 0
另一种选择是:
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
英文:
Another option would be:
df$closest <- colnames(df)[apply(df, 1, which.min)]
using the following df
:
structure(list(x = c(1L, 5L, 3L), y = c(4L, 2L, 6L)), class = "data.frame", row.names = c(NA,
-3L)) -> df
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论