如何获取值最接近于0的列名?

huangapple go评论76阅读模式
英文:

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 &lt;- names(df)[max.col(-abs(df))]
df
#  x y closest
#1 1 4       x
#2 5 2       y
#3 3 6       x

data

df &lt;- structure(list(x = c(1L, 5L, 3L), y = c(4L, 2L, 6L)), class = &quot;data.frame&quot;, 
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 &lt;- colnames(df)[apply(df, 1, which.min)]

using the following df:

structure(list(x = c(1L, 5L, 3L), y = c(4L, 2L, 6L)), class = &quot;data.frame&quot;, row.names = c(NA, 
-3L)) -&gt; df

huangapple
  • 本文由 发表于 2020年1月6日 15:51:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608445.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定