2016-04-15 57 views
0

我被给了几百个excel文件,其中数据以“风格化”格式存储。当我批量转换的文件为.csv并在相关线读,从一个单一的文件中的数据是这样的:来自单个列中多个变量的数据,如何修复? - R dataframe

data.frame(x1= c("year", "2014", "site", "28",NA,NA), x2= LETTERS[1:6]) 
    x1 x2 
1 year A 
2 2014 B 
3 site C 
4 28 D 
5 <NA> E 
6 <NA> F 

我希望它看起来像这样:

data.frame(year= rep("2014",6), site= rep("28",6), x2= LETTERS[1:6]) 
    year site x2 
1 2014 28 A 
2 2014 28 B 
3 2014 28 C 
4 2014 28 D 
5 2014 28 E 
6 2014 28 F 

正如你可以看到,单个列中存储了2个变量名称(年份和地点)及其数据(“2014”和“28”)。 (变量数据总是在变量名后面的行中。)数据框中的其他变量(在本例中为x2)格式正确。

我可以问一些关于如何有效地将这些变量存入自己的列的建议吗?我需要将这个解决方案应用于大约100个不同长度的数据帧,然后才能成为1.

回答

2

在基础R:

df <- data.frame(x1= c("year", "2014", "site", "28",NA,NA), x2= LETTERS[1:6], stringsAsFactors = FALSE) 

一对夫妇的索引:

year_idx <- which(df$x1 == "year") 
site_idx <- which(df$x1 == "site") 

得到它们的值,

year <- df$x1[year_idx +1] 
site <- df$x1[site_idx +1] 

做出新的列使用新值:

df["year"] <- year 
df["site"] <- site 

重排:

df <- df[, c(3,4,2)] 

stylized_rearranger <- function(df) { 
and just do the above steps within and return 
df 
} 
+0

更简单的是,'df $ year < - df $ x1 [其中(df $ x1 ==“year”)+ 1 ]'和'df $ site < - df $ x1 [其中(df $ x1 ==“site”)+ 1]' –

+0

确实,链式符号总是令人惊讶,但我发现我的目的是:然后是链接,一旦我明白了其含义。 – Chris

1

只要跨文件的格式一致(一个大的if),就可以编写代码来清理一个文件,将其放入一个函数中,然后使用`lapply(files,myFunction)将所有文件作为列表读入。在您的示例中,名为DF为了方便:

# code to clean data 
newdf <- data.frame("year"=df$x1[2], "site"=df$x1[4], "x2"=df$x2) 

# wrap this in a function together with read.csv 
myFunction <- function(infile) { 
    df <- read.csv(infile, as.is=T) 
    newdf <- data.frame("year"=df$x1[2], "site"=df$x1[4], "x2"=df$x2) 
    return(newdf) 
} 

然后使用lapply

fileList <-list.files(<path>) 
# new df names, remove .csv or .xlsx extensions, you may need to do a bit more 
dfNames <- gsub("\\..*$", "", fileList) 
# get a list of the data.frames 
dataList <- lapply(fileList, myFunction) 
+0

感谢,这部作品在我的情况,但@克里斯的回答只是一个小更普遍通过利用行的固定顺序并使用它们的相对索引而不是依靠它们的绝对索引 –

+0

下面是我用于循环创建单个数据框的代码:'files <--list.files(pattern = “* .csv”)''do.call(rbind,lapply(files,myFunction))' –

相关问题