【问题标题】:How to swap/shuffle values within a column in R?如何在 R 中的列中交换/随机播放值?
【发布时间】:2020-11-26 09:40:42
【问题描述】:

我想使用单元格交换匿名数据。因此,我想有条件地交换列内的值。

我的数据如下:

Sex     Age    Houeshold_size
 0       95          2
 0       95          3
 1       90          1
 1       90          5
 1       45          1
 1       45          1
 1       34          1
 1       34          1
 1       34          1
 1       34          1

我想给出交换值,这样每个年龄以上的人的家庭规模都为 1。在本例中为 90 岁或以上。所以我的结果必须是这样的:

Sex     Age    Houeshold_size
 0       95          1
 0       95          1
 1       90          1
 1       90          1
 1       45          1
 1       45          1
 1       34          2
 1       34          3
 1       34          5
 1       34          1

我更想知道如何有条件地交换数据而不是解决这个例子,因为它只是我数据的一小部分。

谢谢你帮助我,干杯。

【问题讨论】:

  • 我想你在找ifelse,例如df$Houeshold_size <- ifelse(df$Age >= 90, 1, df$Houeshold_size)

标签: r swap shuffle


【解决方案1】:

您可以使用以下内容:

#Get the index where Age is 90 or higher
inds <- which(df$Age >= 90)
#replace `Houeshold_size` where age is less than 90 with that of inds
df$Houeshold_size[sample(which(df$Age < 90), length(inds))] <- df$Houeshold_size[inds]
#Change household size of inds to 1
df$Houeshold_size[inds] <- 1


#   Sex Age Houeshold_size
#1    0  95              1
#2    0  95              1
#3    1  90              1
#4    1  90              1
#5    1  45              1
#6    1  45              3
#7    1  34              2
#8    1  34              1
#9    1  34              1
#10   1  34              5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 2014-04-02
    • 2017-06-17
    • 2019-06-18
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多