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

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

How to get the column name of the one which value is closest to 0?

问题

Sure, here is the translated code and desired output:

  1. 我有数据框**df1**,我想设置另一列,其名称是值最接近0的列:
  2. **df1**
  3. ```r
  4. x <- c(1, 3,2)
  5. y <- c(2, 1,4)
  6. df1 <- data. frame(x, y)
  7. df1
  8. # x y
  9. #1 1 2
  10. #2 3 1
  11. #3 2 4

期望输出:

  1. # x y closer
  2. #1 1 2 x
  3. #2 3 1 y
  4. #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

  1. x <- c(1, 3,2)
  2. y <- c(2, 1,4)
  3. df1 <- data. frame(x, y)
  4. df1
  5. # x y
  6. #1 1 2
  7. #2 3 1
  8. #3 2 4

The desire output:

  1. # x y closer
  2. #1 1 2 x
  3. #2 3 1 y
  4. #3 2 4 x
  5. </details>
  6. # 答案1
  7. **得分**: 2
  8. Using `max.col`,我们可以得到距离0最近的值的索引
  9. ```R
  10. max.col(-abs(df))
  11. #[1] 1 2 1

要获取列名,我们可以使用这个索引从数据框的names中进行子集选择

  1. df$closest <- names(df)[max.col(-abs(df))]
  2. df
  3. # x y closest
  4. #1 1 4 x
  5. #2 5 2 y
  6. #3 3 6 x

数据

  1. df <- structure(list(x = c(1L, 5L, 3L), y = c(4L, 2L, 6L)), class = "data.frame",
  2. row.names = c(NA, -3L))
英文:

Using max.col we can get the index of value which is closest to 0

  1. max.col(-abs(df))
  2. #[1] 1 2 1

to get column names we can use this index to subset it from names of the dataframe

  1. df$closest &lt;- names(df)[max.col(-abs(df))]
  2. df
  3. # x y closest
  4. #1 1 4 x
  5. #2 5 2 y
  6. #3 3 6 x

data

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

答案2

得分: 0

另一种选择是:

  1. df$closest <- colnames(df)[apply(df, 1, which.min)]

使用以下的 df

  1. 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:

  1. df$closest &lt;- colnames(df)[apply(df, 1, which.min)]

using the following df:

  1. structure(list(x = c(1L, 5L, 3L), y = c(4L, 2L, 6L)), class = &quot;data.frame&quot;, row.names = c(NA,
  2. -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:

确定