所以我试图在data.frame中创建一个看起来像这样的天气数据集
dayPlus1MinTemp | dayPlus1MaxTemp | dayPlus1Conditions | dayPlus2MinTemp | dayPlus2MaxTemp | dayPlus2Conditions | dayPlus3MinTemp | dayPlus3MaxTemp | dayPlus3Conditions
7 | 16 | Clear | 8 | 17 | Cloudy | 19 | 36 | Sunny
我试着制作一个for循环来做到这一点并且无法做到。
dataFrameForecast <- data.frame()
for(i in 1:10) {
buffer1 <- paste0("dayPlus",i,"MinTemp")
buffer2 <- paste0("dayPlus",i,"MaxTemp")
buffer3 <- paste0("dayPlus",i,"Conditions")
assign(buffer1, resForecastTest2inList$forecast$simpleforecast$forecastday[[i]]$low$celsius)
assign(buffer2, resForecastTest2inList$forecast$simpleforecast$forecastday[[i]]$high$celsius)
assign(buffer3, resForecastTest2inList$forecast$simpleforecast$forecastday[[i]]$conditions)
dataFrameForecast <- data.frame(
buffer1 = get(buffer1),
buffer2 = get(buffer2),
buffer3 = get(buffer3)
)
dataFrameForecast <- cbind(dataFrameForecast, dataFrameForecast)
}
我尝试了这个以及其他许多变体,但我没有设法在列名中同时获得我想要的内容,因为我获得了分配给我的动态创建变量的值。
我做错了什么?
答案 0 :(得分:1)
如果我理解:
#it seems that you are using just this part of the list
sublist<-resForecastTest2inList$forecast$simpleforecast$forecastday[1:10]
#get all the lows, highs and conditions
lows<-lapply(sublist,function(x) x$low$celsius)
highs<-lapply(sublist,function(x) x$high$celsius)
cond<-lapply(sublist,function(x) x$conditions)
#set the names
names(lows)<-paste0("dayPlus",1:10,"MinTemp")
names(highs)<-paste0("dayPlus",1:10,"MaxTemp")
names(cond)<-paste0("dayPlus",1:10,"Conditions")
#get the result
res<-do.call(data.frame,c(lows,highs,cond))
#shuffle the result so to have the desired column order
res[t(matrix(seq_along(res),ncol=3))]
上述情况很可能无法奏效,因为您没有提供可重复的示例。但是,了解如何获取包含lapply
的列表以及如何为其设置名称可能很有用。如果这不起作用,至少可以提供lows
,highs
和cond
对象,看看我们是否可以从那里移动。