R从数据帧创建多个2×2表
下一个问题-我在R中创建了以下数据帧R从数据帧创建多个2×2表,r,R,下一个问题-我在R中创建了以下数据帧 x <- as.integer(rnorm(n=1000, mean=10, sd=5)) y <- 1:1000 z <- sample (c(0,1),1000, replace=T) df <- data.frame(x,y,z) # create variables df using x for(i in 1:10){ df[paste0("col",i)] <- ifelse(df$x <i, 1, 0) }
x <- as.integer(rnorm(n=1000, mean=10, sd=5))
y <- 1:1000
z <- sample (c(0,1),1000, replace=T)
df <- data.frame(x,y,z)
# create variables df using x
for(i in 1:10){
df[paste0("col",i)] <- ifelse(df$x <i, 1, 0)
}
# create 2 by 2 tables of z against col1 to col 10
for(i in 1:10){
table[i] <- table (df[paste0("col",i)], df$z)
}
x您编写的代码有几个问题
首先,表
数据对象不存在,因此无法为其分配索引
其次,访问命名项时需要使用“[[”(否则会得到一个子列表)
最后,如果您制作一个列表,它实际上是一系列表对象最合理的存储类型,那么您需要使用“[[”而不是“[”来提取项(而不是子列表)
我还冒昧地将它重命名为tbl
,这样就不会对什么是函数,什么是数据产生认知上的混淆
tbl<- list();
for(i in 1:10){
tbl[[i]] <- table (df[[paste0("col",i)]], df$z)
}
tbl[[1]]
0 1
0 488 473
1 16 23
tblThanks BondedDust运行得很好-我对R和索引仍然很困惑!我能问一下list()后面的分号的用途吗?list()做什么?再次感谢!分号是换行符或新命令分隔符。可以放在换行符中。list()只需使tbl
成为一个空列表…并带有一个名称。