带R的表格 [英] Table by row with R
问题描述
我想在数据框中按行列出.在以下示例中,可以使用apply
中的table
获得足够的结果:
I would like to tabulate by row within a data frame. I can obtain adequate results using table
within apply
in the following example:
df.1 <- read.table(text = '
state county city year1 year2 year3 year4 year5
1 2 4 0 0 0 1 2
2 5 3 10 20 10 NA 10
2 7 1 200 200 NA NA 200
3 1 1 NA NA NA NA NA
', na.strings = "NA", header=TRUE)
tdf <- t(df.1)
apply(tdf[4:nrow(tdf),1:nrow(df.1)], 2, function(x) {table(x, useNA = "ifany")})
以下是结果:
[[1]]
x
0 1 2
3 1 1
[[2]]
x
10 20 <NA>
3 1 1
[[3]]
x
200 <NA>
3 2
[[4]]
x
<NA>
5
但是,在下面的示例中,每一行都包含一个值.
However, in the following example each row consists of a single value.
df.2 <- read.table(text = '
state county city year1 year2 year3 year4 year5
1 2 4 0 0 0 0 0
2 5 3 1 1 1 1 1
2 7 1 2 2 2 2 2
3 1 1 NA NA NA NA NA
', na.strings = "NA", header=TRUE)
tdf.2 <- t(df.2)
apply(tdf.2[4:nrow(tdf.2),1:nrow(df.2)], 2, function(x) {table(x, useNA = "ifany")})
我得到的输出是:
# [1] 5 5 5 5
因此,我不能从此输出中看出前5个代表0,后5个代表1,第3个5代表2,最后5个代表NA.有没有一种方法可以让R返回第二个示例中每个5表示的值?
As such, I cannot tell from this output that the first 5 is for 0, the second 5 is for 1, the third 5 is for 2 and the last 5 is for NA. Is there a way I can have R return the value represented by each 5 in the second example?
推荐答案
以下是table
解决方案:
table(
rep(rownames(df.1),5),
unlist(df.1[,4:8]),
useNA="ifany")
这给
0 1 2 10 20 200 <NA>
1 3 1 1 0 0 0 0
2 0 0 0 3 1 0 1
3 0 0 0 0 0 3 2
4 0 0 0 0 0 0 5
...以及您的df.2
:
0 1 2 <NA>
1 5 0 0 0
2 0 5 0 0
3 0 0 5 0
4 0 0 0 5
好吧,这是一个解决方案,除非您出于某种原因真的很喜欢有一个表列表.
Well, this is a solution unless you really like having a list of tables for some reason.
这篇关于带R的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!