我有一个输入数据文件(例如 pets.csv)作为列联表
举个例子,所以
Animal
Dog Cat
Color
Black 15 20
White 30 60
因此,维度名称是“动物”和“颜色”。有没有办法用维度名称将其读入 R?
目前,我输入文件很简单
Dog Cat
Black 15 20
White 30 60
然后做
mytable<-read.csv("pets.csv", header = TRUE, row.names=1)
但是这会丢失这些变量的名称(Color
和 Animal)
。
我看到我可以将文件完全输入为数字并以暗名称输入名称,但我宁愿只读取文件。我在文件中得到了大量的表格。
最佳答案
我认为你必须为此创建一个自定义函数。假设我们已将上面的表格复制并粘贴到 Excel 中,并将其另存为 animal_colors.csv
。然后你可以设置这样的函数:
read_ctable <- function(x) {
# get the variable names from first two lines
vars <- readLines(x, 2)
# remove comma separators
vars <- gsub(',', '', vars)
# read in data starting on third line
df <- read.csv(x, header=T, row.names=1, skip=2)
# convert to table
dt <- as.table(as.matrix(df))
# add variable names (have to reverse, because of the order in which they appeared in the file)
names(attributes(dt)$dimnames) <- rev(vars)
return(dt)
}
当我对如上所述设置的 CSV 文件调用 read_ctable('animal_colors.csv')
时,输出如下:
Animal
Color Dog Cat
Black 15 20
White 30 60
这是一个 array
对象,在我看来,它不如您通过调用 read.csv
获得的数据框对象有用,但您可以将 调用为.data.frame
以获得一个漂亮整洁的数据框以供进一步分析:
Color Animal Freq
1 Black Dog 15
2 White Dog 30
3 Black Cat 20
4 White Cat 60
关于r - 如何从 R 中带有列联表的文件中读取维度名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76175442/