R中数据帧的列中的第一个非空值

时间:2016-10-13 13:33:21

标签: r dataframe

我有一个数据框,其中有列标题,但是coulmn标题的位置不固定,所以我可以读取第1列中的非空值,以获取处理文件的标题索引。

mydata.txt

                      test   34   45
                      rt     45   56 
                      tet3     67   56
       Col1   Col2    Col3   Col4  Col5
        45    45      23     56    12 
        34    45      67     65    32 
        45    67      78     90    54 
        56    43      32     12    45


   mydata = read.table("mydata.txt")
   mydata[,1]     #how to find first non blank value in first  column?

为了简化about pblm:

DF< -C( “”, “”, “”,34,23,45)

如何在df中找到fiest非空值

2 个答案:

答案 0 :(得分:0)

好的,例如

writeLines(tf <- tempfile(fileext = ".txt"), text = "
             test   34   45
              rt     45   56 
              tet3     67   56
Col1   Col2    Col3   Col4  Col5
45    45      23     56    12 
34    45      67     65    32 
45    67      78     90    54 
56    43      32     12    45")
mydata = read.table(tf, fill = TRUE, stringsAsFactors = FALSE)
idx <- which.min(mydata[,4]=="")
df <- mydata[-(1:idx), ]
df <- as.data.frame(lapply(df, type.convert))
names(df) <- unlist(mydata[idx, ],F,F)

给你

str(df)
# 'data.frame': 4 obs. of  5 variables:
#  $ Col1: int  45 34 45 56
#  $ Col2: int  45 45 67 43
#  $ Col3: int  23 67 78 32
#  $ Col4: int  56 65 90 12
#  $ Col5: int  12 32 54 45

答案 1 :(得分:0)

尝试回答你的&#34;简化&#34;问题:

df <- c("", "", "", 34, 23, 45)

purrr包使用detect()detect_index()提供此类功能:

install.packages("purrr", repos = "https://cloud.r-project.org")
library(purrr)
detect_index(df, function(x) x != "")