简体   繁体   English

R Apply函数列出并创建新的数据框

[英]R Apply function to list and create new dataframe

I am wanting to retrieve data from several webpages that is in the same place on all the pages and put it all in one data frame. 我想从所有页面上位于同一位置的几个网页中检索数据,并将其全部放入一个数据框中。

I have the following code attempt: 我有以下代码尝试:

library(XML)
library(plyr)

**##the urls**
raceyears<-list(url2013,url2012,url2011)

**##function that is not producing what I want**
raceyearfunction<-function(x){
page<-readLines(x)
stats<-page[10:19]
y<-read.table(textConnection(stats))
run<-data.frame(y$V1,y$V2)
colnames(run)<-c("Country","Participants")
rbind.fill(run)
}

data<-llply(raceyears,raceyearfunction)

This places all the data in multiple columns (two columns for each webpage) but I am wanting all the data in two columns (Participants, Country) one data frame not many columns in one data frame. 这会将所有数据放在多列中(每个网页两列),但我希望所有数据都在两列(参与者,国家/地区)中,一个数据帧而不是一个数据帧中有很多列。

I haven't found a question quite like this already on the site but am open to follow a link. 我还没有在网站上找到类似的问题,但是可以打开链接。 Thank you in advance. 先感谢您。

You need to use rbindlist outside of raceyearfunction. 您需要在raceyearfunction之外使用rbindlist。 Let it return(run) without rbind.fill(run) . 让它return(run)而不rbind.fill(run)

You can use ldply instead, then it will return binded data.frame already. 您可以改用ldply,然后它将返回绑定的data.frame。

library(XML)
library(plyr)

raceyears <- list(url2013,url2012,url2011)

raceyearfunction<-function(x)
{
    page <- readLines(x)
    stats <- page[10:19]
    y <- read.table(textConnection(stats))
    run <- data.frame(y$V1,y$V2)
    colnames(run) <- c("Country","Participants")
    return(run)
}
data<-ldply(raceyears, raceyearfunction)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R - 使用 map 将列表函数应用于数据框列并使用列表元素创建新列 - R - using map to apply a list function to dataframe column and create new columns with elements of the list 如何申请 3 function 新建 dataframe - How to apply 3 function to create a new dataframe 如何将 function 应用于列表中 dataframe 中的每个元素,并在 Z6A8064B5DF4794555500553C47C55057DZ 中返回 dataframe - How to apply a function to every element in a dataframe in a list and return a dataframe in R? R Apply功能带有2个数据框 - R apply function with 2 dataframe 将创建列功能应用于列表r - apply create columns function to a list r 使用 apply 从 R 中的 dataframe 创建邻接矩阵列表 - Use apply to create a list of adjacency matrices from dataframe in R 将 function 应用于 dataframe 中的列的每一行以创建新列 - Apply a function to each row of a column in a dataframe to create a new column 尝试将函数rowwise应用于数据框以创建新列 - Trying to apply a function rowwise to a dataframe to create a new column 使用Apply系列功能创建多个新数据框 - Use Apply family function to create multiple new dataframe R 使用 purrr::map 在数据框列表中的选定列上应用函数 - R use purrr::map to apply a function on a selected columns in a dataframe list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM