【问题标题】:Replace random values in a column in a dataframe替换数据框中列中的随机值
【发布时间】:2017-11-11 13:45:29
【问题描述】:

请告知如何将列中的一半值替换为 NA:

# Generate 500 values with a skewed distribution
x1 <- round(rbeta(500,0.5,3)*100,0)

# Assign variable to a data frame
df <- data.frame(x1)

# Replace 250 random values in a column 'x1' to NA
df[sample(x1,250)] <- NA

The following mistake is shown:
Error in `[<-.data.frame`(`*tmp*`, sample(x1, 250), value = NA) : 
  new columns would leave holes after existing columns

我明白为什么会显示错误,但我想强制更换。请告知我该怎么做。

【问题讨论】:

  • 欢迎来到 Stack Overflow,Gregory...看看这个。它将帮助您格式化您的帖子,使其更易于阅读。 stackoverflow.com/editing-help

标签: r replace


【解决方案1】:

看来你需要

df$x1[sample(nrow(df),250)] <- NA

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2019-03-06
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2018-04-03
    相关资源
    最近更新 更多