【问题标题】:How to fill column based on condition taking other columns into account?如何在考虑其他列的情况下根据条件填充列?
【发布时间】:2022-01-06 10:46:05
【问题描述】:

要根据考虑另一列的条件填充数据框的空列,我找到了以下解决方案,它工作正常,但有点难看。有人知道解决这个问题的更优雅的方法吗?

base::set.seed(123)
test_df <- base::data.frame(vec1 = base::sample(base::seq(1, 100, 1), 50), vec2 = base::seq(1, 50, 1), vec3 = NA)

for (a in 1:base::nrow(test_df)){
  spc_test_df <- test_df[a, ]
  # select the specific row of the dataframe
  if(spc_test_df$vec1 <= 25 | spc_test_df$vec1 >= 75){
    # evaluate whether the deviation is below/above the threshold
    spc_test_df$vec3 <- 1
    # if so, write TRUE
  } else {
    spc_test_df$vec3 <- 0
    # if not so, write FALSE
  }
  test_df[a, ] <- spc_test_df
  # write the specific row back to the dataframe
}

【问题讨论】:

  • 您的情况有点奇怪:spc_test_df$vec1 &lt;= 25 | spc_test_df$vec1 &gt;= 25 基本上选择了所有情况;因此一切都设置为1
  • (1) 你的计算应该是矢量化的,不要使用for 循环。 (2) 不要在if 条件句中使用|,除非它被总结(例如,anyall),而是使用||(理由包括短路)。 (3) 同上对ifelse 的引用,可能类似于test_df$vec3 &lt;- ifelse(test_df$vec1 &lt;= 25, 1, 0),或者,因为是/否值是1 和0,最好是test_df$vec3 &lt;- +(test_df$vec1 &lt;= 25)(以及你对逻辑下半场的真正含义,. &lt;= 25 | . &gt;= 25肯定令人困惑)。
  • 对不起,我编辑了这个问题。非常感谢您到目前为止的回答:)

标签: r dataframe for-loop dplyr


【解决方案1】:

不需要 for 循环,因为在这种情况下您可以使用矢量化解决方案。关于如何解决这个问题的三个选项:

# option 1
test_df$vec3 <- +(test_df$vec1 <= 25 | test_df$vec1 >= 75)

# option 2
test_df$vec3 <- as.integer(test_df$vec1 <= 25 | test_df$vec1 >= 75)

# option 3
test_df$vec3 <- ifelse(test_df$vec1 <= 25 | test_df$vec1 >= 75, 1, 0)

在所有情况下都会给出:

   vec1 vec2 vec3
1     5    1    1
2     6    2    1
3    61    3    0
4    20    4    1

....

47    3   47    1
48   55   48    0
49   44   49    0
50   97   50    1

(仅显示第一行和最后四行)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    相关资源
    最近更新 更多