问题
what i am trying to implement is to write an R hashtable to a csv file excel ( column like formatted file- keys in first column and values in the second). please consider this example. (the hash table is created by hash package)
<hash> containing 5 key-value pair(s).
1 : 4
2 : NULL
3 : NULL
4 : 3 1
5 : 1 4
when I simply use this
write.csv(hash, file = "hash.csv",row.names=FALSE)
it gives me this error
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class "structure("hash", package = "hash")" to a data.frame
so i try to create a dataframe from each key and values and then bind them:
a<-as.data.frame(keys(hash))
b<-as.data.frame(values(hash))
Error in data.frame(`1` = "4", `2` = NULL, `3` = NULL, `4` = c("3", "1" :
arguments imply differing number of rows: 1, 0, 2
then to create a list and a vector :
a<-keys(hash)
b<-values(hash)
d<-cbind(a,b)
f<-as.data.frame(d)
a b
1 1 4
2 2 NULL
3 3 NULL
4 4 3, 1
5 5 1, 4
but then when I try to write it:
write.csv(f, file = "hash.csv",row.names=FALSE)
Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol, :
unimplemented type 'list' in 'EncodeElement'
so is there any other way to do that or any way to fix this error ? thank you in advance.
回答1:
this somehow help me. but it is not yet the answer of my question as I was looking for a better solution.
a<-keys(hash)
b<-values(hash)
d<-cbind(a,b)
L<-as.data.frame(d)
L.df <- data.frame(lapply(L, as.character), stringsAsFactors=FALSE)
write.csv(f.df, file ="file.CSV",row.names=FALSE)
csv file format
# a b
# 1 4
# 2 NULL
# 3 NULL
# 4 c("3", "1")
# 5 c("1", "4")
来源:https://stackoverflow.com/questions/30165162/writing-a-r-hashtable-in-to-a-csv-file