我需要改变数据帧的行,转而:
A foo
B bar
C baz
进入这个:
B foo
C bar
A baz
即,第一列应该进行洗牌,同时保持其余部分不变。我是根据建议here使用sample()
库中的kimisc
来执行此操作的。最小的工作代码示例是:
>df<-read.table("file1", header=F, skip=1)
>library(kimisc)
>names<-read.table("file2")
>df1<- transform(sample(df,size=nrow(names)),V1=names)
>df1
V1 V2
5 A 21266
8 C 22109
7 F 17971
1 J 11137
file1
Name Value
A 28463
B 11137
C 24966
D 24611
E 14980
F 21266
G 23441
H 17971
I 22109
J 31746
和file2
是:
A
C
F
J
然后,我想将此数据帧写入文件,我的预期输出是
A 21266
C 22109
F 17971
J 11137
然而,加载kimisc
库提供了自己的sample
函数(与香草不同)按照我想要的方式对数据框进行洗牌,但似乎搞砸了打印:
write.table(df1,“file3”,quote = F,sep ='\ t',col = FALSE)
这会产生以下输出:
5 1:4 21266
8 1:4 22109
7 1:4 17971
1 1:4 11137
如果我使用vanilla sample
,生成的数据框将按预期打印,但不会以我需要的方式进行洗牌(即,列而不是行被洗牌)。
那么,我怎样才能使用sample
中的kimisc
,这样我就可以对行而不是数据框的列进行采样,并且仍然可以将其打印出来write.table
可以使用base::sample
返回的数据框吗?
PS。我正在使用名单列表,因为我实际上是在尝试将包含143558041行的文件中的随机值分配给该文件中提到的名称的子集(39953)。
根据要求,dput(df1)
的输出为
> dput(df1)
structure(list(V1 = structure(list(V1 = structure(1:4, .Label = c("A",
"C", "F", "J"), class = "factor")), .Names = "V1", class = "data.frame", row.names = c(NA,
-4L)), V2 = c(24611L, 14980L, 22109L, 21266L)), .Names = c("V1",
"V2"), row.names = c(3L, 4L, 8L, 5L), class = "data.frame")
答案 0 :(得分:1)
我已将您的输入重新设计为reproducible example:
library(kimisc)
## Loading required package: Rcpp
## Loading required package: logging
set.seed(20130828L)
df <- read.table(text="Name Value
A 28463
B 11137
C 24966
D 24611
E 14980
F 21266
G 23441
H 17971
I 22109
J 31746", header=F, skip=1)
names <- read.table(text="A
C
F
J")
df.s <- sample.data.frame(df,size=nrow(names))
df1<- transform(df.s,V1=names)
dput(df1)
## structure(list(V1 = structure(list(V1 = structure(1:4, .Label = c("A",
## "C", "F", "J"), class = "factor")), .Names = "V1", class = "data.frame", row.names = c(NA,
## -4L)), V2 = c(14980L, 21266L, 17971L, 24966L)), .Names = c("V1",
## "V2"), row.names = c(5L, 6L, 8L, 3L), class = "data.frame")
如您所见,生成的dput
输出与您的类似。
实际上,names
是嵌入到另一个数据帧中的数据帧。这与sample.data.frame
中的问题无关。两种可能的补救措施:
names$V1
来电transform
names
视为向量而不是表格(小心nrow(names)
)