本文介绍了有条件地将行添加到data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在一个30年的调查中,我在一家工厂花了大量的 ## x是您在问题中给出的数据框x< - data.frame(年= c(2004,2004,2005,2005),月= c(6,7,7,8),花= c(25,48,20,16), Fruits = c(2,4,1,1)) ##是数据帧提供缺失值 ##,以便您可以使用< - expand.grid(Year = 2004: 2005,月= 1:12) ##这最后一步填补缺失日期并用零代替NA's library(tidyr)x< - merge (x,y,all = TRUE)%>% replace_na(list(Flowers = 0,Fruits = 0)) ##如果你不想使用tidyr,您也可以做 x< - merge(x,y,all = TRUE)x [is.na(x)] 它看起来像这样: head (x,10) #年份鲜花水果#1 2004 1 0 0 #2 2004 2 0 0 #3 2004 3 0 0 #4 2004 4 0 0 #5 2004 5 0 0 #6 2004 6 25 2 #7 2004 7 48 4 #8 2004 8 0 0 #9 2004 9 0 0 #10 2004 10 0 0 I have a big data.frame of flowers and fruits in a plant for a 30 years survey. I want to add zeros (0) in some rows which represent individuals in specific months where the plant did not have flowers or fruits (because it is a seasonal species).Example: Year Month Flowers Fruits2004 6 25 22004 7 48 42005 7 20 12005 8 16 1I want to add the months that are not included with values of zero so I was thinking in a function that recognize the missing months and fill them with 0.Thanks. 解决方案 ## x is the data frame you gave in the questionx <- data.frame( Year = c(2004, 2004, 2005, 2005), Month = c(6, 7, 7, 8), Flowers = c(25, 48, 20, 16), Fruits = c(2, 4, 1, 1))## y is the data frame that will provide the missing values,## so you can replace 2004 and 2005 with whatever your desired## time interval isy <- expand.grid(Year = 2004:2005, Month = 1:12)## this final step fills in missing dates and replaces NA's with zeroslibrary(tidyr)x <- merge(x, y, all = TRUE) %>% replace_na(list(Flowers = 0, Fruits = 0))## if you don't want to use tidyr, you can alternatively dox <- merge(x, y, all = TRUE)x[is.na(x)] <- 0It looks like this:head(x, 10)# Year Month Flowers Fruits# 1 2004 1 0 0# 2 2004 2 0 0# 3 2004 3 0 0# 4 2004 4 0 0# 5 2004 5 0 0# 6 2004 6 25 2# 7 2004 7 48 4# 8 2004 8 0 0# 9 2004 9 0 0# 10 2004 10 0 0 这篇关于有条件地将行添加到data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-03 01:13