r - 如何从 R 数据框的两列中联合采样?
问题描述
我有一个 4 列的数据框。我正在尝试将数据框的两列混在一起,以使这两列始终相关。
我已经尝试过“示例”功能,但它仅限于一列数据框。
data = data.frame(label=letters[1:5], label2=letters[1:15], number=11:15)
data = within(data, numbersq <- (number*number))
# lable lable2 number numbersq
# a a 11 121
# b b 12 144
# c c 13 169
# d d 14 196
# e e 15 225
#Now, I want to twick the data something like, columns 'lable' and 'lable2' remains as it is and columns 'number' and 'numbersq' should shufffle.
#As you can see in the desired output,'number' and 'numbersq' should shuffled together not separately.
#Desired Output
# lable lable2 number numbersq
# a a 15 225
# b b 13 169
# c c 14 196
# d d 12 144
# e e 11 121
I have tried he following code but seems it shuffles the columns separately.
data_2 = data.frame(data_2$label, data_2$label2, sample(data_2$number), sample(data_2$numbersq))
解决方案
非常感谢您的建议。最后我得到了解决方案。代码如下。我相信代码仍然可以优化。
data <- data.frame(label=letters[1:5], lable2=letters[1:5], number=11:15)
data = within(data, numbersq <- (number*number))
print(data)
# lable lable2 number numbersq
# a a 11 121
# b b 12 144
# c c 13 169
# d d 14 196
# e e 15 225
data_2a = data[,1:2]
data_2b = data[,3:4]
data_2b_samp = data_2b[sample(nrow(data_2b)), ]
data_3 = cbind(data_2a, data_2b_samp)
print(data_3)
# lable lable2 number numbersq
# a a 15 225
# b b 13 169
# c c 14 196
# d d 12 144
# e e 11 121
推荐阅读
- android-studio - Android Studio 模拟器错误“模拟器:CPU 加速状态:无法打开 HAXM 设备:ERROR_FILE_NOT_FOUND”
- r - 按组拆分 PCA 图
- datasource - websphere-DSRA0010E 中的测试连接失败:SQL 状态 = S0001,错误代码 = 18,456
- sql-server - 更新后触发以更新链接服务器表
- javascript - Svelte 不包括 bundle 中的计算属性。不产生错误
- c# - 如何使 C++ 编译器遵循 C# 在 this 赋值语句中的相同优先级、关联性和求值顺序?
- python - 连接具有相同 ID Pandas DataFrame 的列
- c# - 如何使用正则表达式在起始文本和结束字符之间获取字符串?
- css - 如何使svg图像高于其他元素
- sql - 默认情况下显示 Oracle Apex 选择列表