进行“下拉" R中的功能 [英] making a "dropdown" function in R

查看:68
本文介绍了进行“下拉" R中的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我会以excel电子表格的格式获取数据,如下所示:

Often times I get data in the format of an excel spreadsheet that looks like:

Name1 Data
      Data
      Data  
Name2 Data
      Data
      Data
....

当我将其读入R时,空白行以NA的形式出现,然后我总是编写一些临时代码来填充它,使其看起来像:

When I read this into R, the blank rows come us as NA and then I always write some ad hoc code to fill it in so that it looks like:

Name1 Data
Name1 Data
Name1 Data
Name2 Data
Name2 Data
Name2 Data
....

通常,我只是使用for循环来执行此操作,该循环会跟踪姓氏,并且每次看到我填写的NA时都会进行跟踪.下次当我在name列中看到内容时,然后保存新名称并开始写那个.

Typically, I just do this with a for loop that keeps track of the last name and every time I see an NA I fill it in. The next time I see something in the name column, I then save the new name and start writing that.

我想知道是否有更漂亮的R矢量版本?

I was wondering if there was a prettier, R vectorized version of that?

谢谢!

推荐答案

您可以尝试

  indx <- !is.na(df$Col1)
  df$Col1 <- df$Col1[indx][cumsum(indx)] 
  df
  #   Col1 Col2
  #1 Name1 Data
  #2 Name1 Data
  #3 Name1 Data
  #4 Name2 Data
  #5 Name2 Data
  #6 Name2 Data

数据

df <- structure(list(Col1 = c("Name1", NA, NA, "Name2", NA, NA),
 Col2 = c("Data", "Data", "Data", "Data", "Data", "Data")), .Names = c("Col1", 
"Col2"), class = "data.frame", row.names = c(NA, -6L))

这篇关于进行“下拉" R中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆