我有多个具有双列结构的csv文件。一旦文件在R中,如下所示
# A tibble: 18 x 3
# Groups: group [2]
V1 V2 group
<chr> <chr> <int>
1 Sample File "C:\\Data\\CPC\\COALA_CPC3776_20200129.xls" 0
2 Model "3776" 0
3 Sample # "1" 1
4 Start Date "01/29/20" 1
5 Start Time "03:06:08" 1
6 Sample Length "04:58" 1
7 Averaging Interval (secs) "1.0" 1
8 Title "" 1
9 Instrument ID "3776 70634317 2.7" 1
10 Instrument Errors "None" 1
11 Mean "4687.93" 1
12 Min "4215" 1
13 Max "5095" 1
14 Std. Dev. "208.445" 1
15 Time "Concentration (#/cm³)" 1
16 03:06:09 "4581" 1
17 03:06:10 "4673" 1
18 03:06:11 "4657" 1此格式每5分钟重复一次。我希望将日期和示例#移动到新列,然后删除示例文件之间的所有其他行到Std.Dev。在V1中得到这样的东西。
time concentration date sample
1 02:02:02 1200 01/01/01 2
2 02:02:03 1300 01/01/01 2
3 02:03:03 4000 01/01/01 2我可以根据样本#对数据进行分组,但是我不知道如何处理。到目前为止,这是我的代码
cpc_files <- list.files(pattern = '*.xls',path = 'input/CPC/')
cpc_raw <- do.call("rbind", ##Apply the bind to the files
lapply(cpc_files, ##call the list
function(x) ##apply the next function
read.table(paste("input/CPC/", x, sep=''),sep=',',fill = T, header = F,
stringsAsFactors = FALSE,comment.char = "",
col.names = paste0("V",seq_len(max(count.fields("input/CPC/COALA_CPC3776_20200129.xls", sep = ','))))))) ##Read all the files filling the blanks with NAs
cpc_fix <- cpc_raw%>%select(V1,V2)%>%
group_by(group = cumsum(V1 == "Sample #"))发布于 2020-02-24 00:21:00
我把这个过程分解成两个部分:
ungroup()
cpc_clean <- cpc_fix[grep(pattern="0-90-90-9",cpc_fix$V1,perl=TRUE)
名称(Cpc_clean) <- c(“时间”、“浓度”、“组”、“日期”、“样本”)
发布于 2020-02-21 05:54:39
我将您的输入简化为2列,但这应该是一个好的开始。
x <- read.csv(file = '~/file.csv', stringsAsFactors = F)
df <- cbind(t(x$V2[1:(which('Time'==x$V1)-1)]),
x[(which('Time'==x$V1)+1):nrow(x),], stringsAsFactors = F)
colnames(df) <- unlist(c(x$V1[1:(which('Time'==x$V1)-1)],
x[(which('Time'==x$V1)),]))cbind的第一个参数是元数据(第1行到它找到'Time'的位置),第二个参数是示例('Time'之后的所有内容)。设置列名的相同逻辑。如果需要,还可以将名称存储为一行。
df2 <- rbind(colnames(df), df)https://stackoverflow.com/questions/60331020
复制相似问题