R 如何将列的级别更改为数据帧中的新行,而不丢失另一列的值?
我希望将列的级别设置为数据帧中的新行。问题是在另一列中为这些级别指定了一个值,我不希望它们丢失。似乎有些行在两个级别上具有相同的名称,因此我希望将to级别保留为列,并为以前的重复项获取唯一的行。下面是我的例子R 如何将列的级别更改为数据帧中的新行,而不丢失另一列的值?,r,R,我希望将列的级别设置为数据帧中的新行。问题是在另一列中为这些级别指定了一个值,我不希望它们丢失。似乎有些行在两个级别上具有相同的名称,因此我希望将to级别保留为列,并为以前的重复项获取唯一的行。下面是我的例子 > shall.will.table<-read.table(choose.files(), header=T, sep="\t", comment.char="") # loads 1000 observations of 3 variables > attach(sh
> shall.will.table<-read.table(choose.files(), header=T, sep="\t", comment.char="") # loads 1000 observations of 3 variables
> attach(shall.will.table)
> head(shall.will.table)
CX VERB FREQ
1 shall be 4414
2 shall have 1354
3 shall see 1131
4 shall go 521
5 shall do 482
6 shall take 356
> ordering.index<-order(VERB, CX)
> shall.will.table.2<-shall.will.table[ordering.index,]
> head(shall.will.table.2)
CX VERB FREQ
912 will abandon 43
384 shall abide 4
896 will abolish 47
104 shall accept 24
565 will accept 524
171 shall accompany 14
>shall.will.table附件(shall.will.table)
>头部(应。将。表)
动词频率
1应为4414
2应为1354
3应参见1131
4.我要走了
5个就够了
6乘356
>订购.索引应.将.表2标题(应.将.表2)
动词频率
912将放弃43
384应遵守第4条
896将废除47
104应接受24
565将接受524
171应与14一起提供
我希望得到的输出应该如下表所示,但不经过以下步骤:
> VERB<-c("abandon", "abide", "abolish", "accept", "accompany")
> shall<-c(0, 4, 0, 24, 14)
> will<-c(43, 0, 47, 524, 0)
> shall.will.table.3<-data.frame(VERB, shall, will)
> shall.will.table.3
VERB shall will
1 abandon 0 43
2 abide 4 0
3 abolish 0 47
4 accept 24 524
5 accompany 14 0
>动词shall-shall.will.table.3 shall.will.table.3
动词应为
1放弃0 43
2.4.0
3废除0 47
4接受24 524
5.14.0
有人能帮我吗
提前感谢。您可以尝试使用软件包
tidyr
,以及功能spread
。这将把长数据转换为宽数据:
library(tidyr)
shall.will.table %>% spread(CX, FREQ, fill = 0)
VERB shall will
1 abandon 0 43
2 abide 4 0
3 abolish 0 47
4 accept 24 524
5 accompany 14 0
或者您可以使用
reformae2
软件包
require(reshape2)
dcast(shall.will.table.2, VERB~CX, value.var = "FREQ", fill=0)
除非有明确的原因,否则最好不要指定fill
参数