在数据集中填写每个ID的N / As

时间:2018-03-12 07:47:20

标签: r na

我在R中的数据集如下所示,其中我有多个ID和年份但不总是街道,州和国家的信息。

ID   Year   Street        State   Country
1    2000   123 Main St   CA      USA
1    2001   N/A           N/A     N/A     
1    2002   N/A           N/A     N/A
...
1    2017   N/A           N/A     N/A
2    2001   123 Bloom Rd  CA      USA
2    2002   123 Bloom Rd  CA      USA
2    2003   N/A           N/A     N/A
...
2    2017   N/A           N/A     N/A
...

我的目标是用适当的值填写N / A,即每个ID的相应值。因此对于ID" 1"应该有" 123 Main Street"在街道N / As等等。

谢谢!

2 个答案:

答案 0 :(得分:2)

这里是data.tbale和dplyr

的解决方案
df <- read.table(text = "ID,   Year,   Street,        State,   Country
1,    2000,   123 Main St,   CA,      USA
1,    2001,   N/A,           N/A,     N/A     
1,    2002,   N/A,           N/A,     N/A
1,    2017,   N/A,           N/A,     N/A
2,   2001,   123 Bloom Rd,  CA,      USA
2,   2002,   123 Bloom Rd,  CA,      USA
2,    2003,   N/A,           N/A,     N/A
2,    2017,   N/A,           N/A,     N/A",header = T,sep = ",")

library(dplyr)
df %>% 
  group_by(ID) %>% 
  mutate_at(vars('Street', 'State', 'Country'), funs(.[!is.na(.)][1]))

library(data.table)
df <- setDT(df)
coltochange <- c("Street", "State", "Country")
df[, c(coltochange) := lapply(.SD,function(x){x[!is.na(x)][1]}),.SDcols = coltochange ,by = ID]

您可以考虑来自zoo的na.locf函数:

library(zoo)
na.locf(df)

答案 1 :(得分:0)

尝试tidyverse方法:

df <- read_table("ID Year Street State Country #importing the data
1 2000 123_Main_St CA USA
1 2001 N/A N/A N/A     
1 2002 N/A N/A N/A
1 2017 N/A N/A N/A
2 2001 123_Bloom_Rd CA USA
2 2002 123_Bloom_Rd CA USA
2 2003 N/A N/A N/A
2 2017 N/A N/A N/A") %>% 
  separate("ID Year Street State Country", c("ID", "Year", "Street", "State", "Country"), sep = " ") %>% # cleaning the columns
  group_by(ID) %>% # grouping by vars with same ID(Information)
  mutate_at(vars('Street', 'State', 'Country'), funs(.[.!= "N/A"][1])) # replace NA with information of same ID without NA (remember NA is still a string from import)