2016-07-27 63 views
1

我得到CSV的数百个不同的列,并希望能够输出一个新的文件,并从每列中删除重复的值。我所见过并尝试过的所有东西都使用了特定的列。我只需要每列都是唯一的值。R删除每列中的重复数据

比如我的数据:

df <- data.frame(A = c(1, 2, 3, 4, 5, 6), B = c(1, 0, 1, 0, 0, 1), C = c("Mr.","Mr.","Mrs.","Miss","Mr.","Mrs.")) 
df 
    A B C 
    1 1 1 Mr. 
    2 2 0 Mr. 
    3 3 1 Mrs. 
    4 4 0 Miss 
    5 5 0 Mr. 
    6 6 1 Mrs. 

我想:

A B C 
    1 1 1 Mr. 
    2 2 0 Mrs. 
    3 3 Miss 
    4 4 
    5 5  
    6 6 

然后我就可以:

write.csv(df, file = file.path(df, "df_No_Dupes.csv"), na="") 

所以我可以用它作为参考我的下一个任务。

回答

0
df <- data.frame(A = c(1, 2, 3, 4, 5, 6), B = c(1, 0, 1, 0, 0, 1), C = c("Mr.","Mr.","Mrs.","Miss","Mr.","Mrs.")) 


for(i in 1:ncol(df)){ 
    assign(paste("df_",i,sep=""), unique(df[,i])) 
} 

require(rowr) 
df <- cbind.fill(df_1,df_2,df_3, fill = NA) 
V1 V1 V1 
1 1 1 Mr. 
2 2 0 Mrs. 
3 3 NA Miss 
4 4 NA <NA> 
5 5 NA <NA> 
6 6 NA <NA> 

,或者你可以做

require(rowr) 
df <- cbind.fill(df_1,df_2,df_3, fill = "") 
df 
V1 V1 V1 
1 1 1 Mr. 
2 2 0 Mrs. 
3 3 Miss 
4 4   
5 5   
6 6 

如果你想避免输入你可以使用ls(pattern="df_")每个中间数据框的名称和get在该向量中命名的对象或使用另一个循环。

如果你想改变列名回到其原始值,你可以使用:

colnames(output_df) <- colnames(input_df) 

然后你就可以将结果保存无论你一样,即

saveRDS()

save()

或将其写入文件。与表格数据

df <- data.frame(A = c(1, 2, 3, 4, 5, 6), B = c(1, 0, 1, 0, 0, 1), C = c("Mr.","Mr.","Mrs.","Miss","Mr.","Mrs.")) 


for(i in 1:ncol(df)){ 
    assign(paste("df_",i,sep=""), unique(df[,i])) 
} 

require(rowr) 
files  <- ls(pattern="df_") 

df_output <- data.frame() 
for(i in files){ 
    df_output <- cbind.fill(df_output, get(i), fill = "") 
} 

df_output <- df_output[,2:4] # fix extra colname from initialization 
colnames(df_output) <- colnames(df) 
write.csv(df_output, "df_out.csv",row.names = F) 

verify_it_worked <- read.csv("df_out.csv") 
verify_it_worked 
A B C 
1 1 1 Mr. 
2 2 0 Mrs. 
3 3 Miss 
4 4  
5 5  
6 6 
+0

这适用于当前的数据集,但是我有时有100个以上的列,以便打字df_1, df_2 ...不起作用。因此,在For循环中,当我将每列输出为值时,我可以运行另一个循环来获取以df_开头的每个值,并合并为1个文件?此外,如果标题可能是完美的原始名称。 – Trigs

+0

@Trigs是的,当然。你也可以使用'ls()'来获得你的环境中的对象列表,使用'pattern',即'ls(pattern =“df _”)'。如果你想改变它的名称,它只是'colnames(output_df)< - colnames(input_df)' –

+0

@Trigs我更新了答案 –

1

read.csvwrite.csv工作最好:

全部放在一起。您所需的输出不是一个很好的例子(每一行没有相同数量的列)。

您可以轻松地得到您的所有列的独特价值与

vals <- sapply(df, unique) 

那么你会更好用节约和save()load()对象列表保存下来作为R对象。

1

代码片段与列的灵活号上班,除去重复列,并保留列名:

require(rowr) 

df <- data.frame(A = c(1, 2, 3, 4, 5, 6), B = c(1, 0, 1, 0, 0, 1), C = c("Mr.","Mr.","Mrs.","Miss","Mr.","Mrs.")) 

#get the number of columns in the dataframe 
n <- ncol(df) 

#loop through the columns 
for(i in 1:ncol(df)){ 

    #replicate column i without duplicates, fill blanks with NAs 
    df <- cbind.fill(df,unique(df[,1]), fill = NA) 
    #rename the new column 
    colnames(df)[n+1] <- colnames(df)[1] 
    #delete the old column 
    df[,1] <- NULL 
}