根据R中的行拆分数据帧

时间:2014-03-24 09:25:57

标签: r

我在PDF文件中有一个表格。我将其转换为CSV,这是CSV内容。

A   23  45  53  34
    62  87  94  75

B   120 61  113 41
    109 48  90  95
    123 113 112 101

我将CSV加载到R中,但数据帧不符合预期。

A   23  45  53  34  62  87  94  75

B   120 61  113 41  109 48  90  95  123 113 112 101 

如何拆分数据框中的行。任何帮助表示赞赏。

最后,我试图实现类似的目标:

A1  23  45  53  34
A2  62  87  94  75

B1  120 61  113 41
B2  109 48  90  95
B3  123 113 112 101

非常感谢

3 个答案:

答案 0 :(得分:1)

这可能会奏效,但您确实无法提供足够的信息来确定。

dat <- readLines("thefile.csv")

prev.x <- ""
ctr <- 1

df <- ldply(strsplit(dat, "\ +"), function(x) { 

  if (nchar(x[1]) == 0) {
    x[1] <- prev.x
    ctr <- ctr + 1
  } else {
    prev.x <<- x[1]
    ctr <- 1
  }  

  x[1] <- sprintf("%s%d", x[1], ctr)

  return(as.data.frame(matrix(x, nrow=1)))

})

colnames(df) <- c("ltr", "v1", "v2", "v3", "V4")

df <- df[complete.cases(df),]
df

答案 1 :(得分:1)

这会有用吗?

x <-read.csv("your-file.csv", header=F)

h=vector("character",nrow(x)) 
n=1; p=NA 
for (i in 1:nrow(x)) { 
  if (""==x$V1[i]) { n=n+1; z = p} else { n = 1; z = p = x$V1[i] }
  h[i] = paste0(z,n)  
}

x$V1 <- h

可能有更好的解决方案,没有for循环,但这是我能设计得最快的......

答案 2 :(得分:1)

另一种可能性:

# read data
df <- read.table(text = "A   23  45  53  34  62  87  94  75
B   120 61  113 41  109 48  90  95  123 113 112 101", fill = TRUE)

df
#   V1  V2 V3  V4 V5  V6 V7 V8 V9 V10 V11 V12 V13
# 1  A  23 45  53 34  62 87 94 75  NA  NA  NA  NA
# 2  B 120 61 113 41 109 48 90 95 123 113 112 101

# from df, remove first column
# then, make a four-column matrix of the non-NA values in each row
l <- apply(df[ , -1], 1, function(x) matrix(na.omit(x), ncol = 4, byrow = TRUE))
l
# [[1]]
#      [,1] [,2] [,3] [,4]
# [1,]   23   45   53   34
# [2,]   62   87   94   75
# 
# [[2]]
#      [,1] [,2] [,3] [,4]
# [1,]  120   61  113   41
# [2,]  109   48   90   95
# [3,]  123  113  112  101

# add id column
lapply(seq_along(l), function(x){
  cbind.data.frame(id = paste0(df$V1[x], seq(from = 1, to = nrow(l[[x]]))), l[[x]])
})

# [[1]]
#   id  1  2  3  4
# 1 A1 23 45 53 34
# 2 A2 62 87 94 75
# 
# [[2]]
#   id   1   2   3   4
# 1 B1 120  61 113  41
# 2 B2 109  48  90  95
# 3 B3 123 113 112 101