Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中交换/洗牌列中的值?_R_Swap_Shuffle - Fatal编程技术网

如何在R中交换/洗牌列中的值?

如何在R中交换/洗牌列中的值?,r,swap,shuffle,R,Swap,Shuffle,我想使用单元交换来匿名化数据。因此,我希望有条件地交换列中的值 我的数据如下所示: 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

我想使用单元交换来匿名化数据。因此,我希望有条件地交换列中的值

我的数据如下所示:

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

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


谢谢您的帮助,干杯。

您可以使用以下选项:

#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
#获取年龄在90岁或以上的索引
inds=90)
#将年龄小于90岁的“Household_尺寸”替换为IND尺寸

df$houshold_size[样本(df$Age<90),length(inds))]我认为您正在寻找
ifelse
,例如
df$houshold_size=90,1,df$houshold_size)