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>
またはあなたがちょうどls(pattern="df_")
を使用することができ、各中間データフレームの名前を入力しないようにしたい場合は、
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
を行うことができ、そのベクトルに指定されたオブジェクトを使用するか、別のループを使用します。あなたが戻って元の値に列名を変更したい場合は
あなたが使用することができます。
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
これは、現在のデータセットのために働く、しかし私は時々、100の以上の列がそうdf_1を入力する必要があり、 df_2 ...は動作しません。ですから、Forループの後にすべての列を値に出力すると、df_で始まるすべての値を取得して1つのファイルに結合する別のループを実行できますか?また、ヘッダーが完全である元の名前である場合もあります。 – Trigs
@Trigsはい、確かです。 'ls(pattern =" df _ ")'という特定の 'pattern 'を持つ環境内のオブジェクトのリストを取得するには' ls() 'を使うこともできます。あなたがその名前を変更したいのであれば、それはちょうど 'colnames(output_df)< - colnames(input_df)'です。 –
@Trigs答えを更新しました –