假设我有一个数据
DF1:
Y1 Y2 Y3
1 1-5 6-10 11-15 #age-groups
2 3 2 2 #number of people per age-group
DF2:
ID Age-Group
1 NA
2 NA
3 NA
4 NA
5 NA
6 NA
7 NA我想在DF1的年龄组列中添加来自DF2的数据:
DF2:
ID Age-Group
1 1-5
2 1-5
3 1-5
4 6-10
5 6-10
6 11-15
7 11-15到目前为止,我有一个循环:
for (i in 1:3) #number of columns in DF1
{number=DF1[2,i] #stores the number of times Age-Group 1-5 is repeated (3)
DF2[1:number,2]=DF1[1,i] #attach the 1-5 label to the first 3 cells这个循环将适用于第一个年龄组1-5,但当我移动到下一个标签时,6-10.如何填充从第4行开始的2个空单元格?从现在开始,循环总是从第1行开始,我的数据比第1行要大得多,这就是为什么循环更好的原因。
发布于 2016-02-07 04:05:25
首先,我假设df1的列不是因素。执行此操作的一个简单方法是使用:
df1[] <- lapply(df1, as.character)您可以使用函数rep()。需要注意的是,rep()接受向量作为第一个和第二个参数的输入,因此这里不需要使用for循环。相反:
df2[, 1] <- unlist(rep(df1[1, ], df1[2, ]))这里,我们告诉rep()重复第一个年龄组"1-5“3次,"6-10”2次等等。rep()的输出将是一个列表,因此unlist()可以用来将一个列表转换为一个向量。
发布于 2016-02-07 04:36:35
我认为斯科特的回答最好。下面是一种显式使用for循环的方法:
a=data.frame()
for (i in 1:nrow(t(DF1)))
{
b<-data.frame(AGE=rep(t(DF1)[i,1],(as.numeric(t(DF1)[i,2]))))
a<-rbind(a,b)
}https://stackoverflow.com/questions/35249210
复制相似问题