英文:
using table() with for loop
问题
df <- data.frame(class=c('A', 'B'),
var2=c(1, 0),
var3=c(0, 1))
for (i in colnames(df)[2:3]) {
#print(i)
table(paste0('df$', i), df$class)
}
运行结果:
<!-- language: lang-none -->
Error in table(paste0("df$", i), df$class) :
all arguments must have the same length
也尝试过将
```R
get(paste0('df$',i))
是否有一种方法可以循环遍历这些列并制表?
英文:
df <- data.frame(class=c('A', 'B'),
var2=c(1, 0),
var3=c(0, 1))
for (i in colnames(df)[2:3]) {
#print(i)
table(paste0('df$', i), df$class)
}
results in
<!-- language: lang-none -->
Error in table(paste0("df$", i), df$class) :
all arguments must have the same length
Also tried putting
get(paste0('df$',i))
Is there a way to loop through these columns and tabulate?
答案1
得分: 2
除了将列制表之外,关于你的首选输出没有太多具体信息,但这里有一个可能的解决方案:
```R
# 这是你的数据框(df):
class<- c('A','B')
var2<- c(1,0)
var3 <- c(0,1)
df<- data.frame(class,var2,var3)
head(df)
class var2 var3
1 A 1 0
2 B 0 1
# 使用lapply制表每一列,输出是一个表格列表:
dftable <- lapply(df, table)
输出看起来是这样的:
> dftb
$class
A B
1 1
$var2
0 1
1 1
$var3
0 1
1 1
purr
包(属于tidyverse)中的map()
函数也可以使用:
library(purrr)
df %>%
map(table) # 产生相同的输出
<details>
<summary>英文:</summary>
Not much info on what exactly your preferred output is other than it tabulates the columns, but here's a potential solution:
This is your df:
class<- c('A','B')
var2<- c(1,0)
var3 <- c(0,1)
df<- data.frame(class,var2,var3)
head(df)
class var2 var3
1 A 1 0
2 B 0 1
Using lapply to tabulate each column. The output is a list of tables:
dftable <- lapply(df, table)
The output looks like this:
> dftb
$class
A B
1 1
$var2
0 1
1 1
$var3
0 1
1 1
The `map()` function from the `purr` package (part of tidyverse) can also be used:
library(purrr)
df|>
map(table) # produces same output
</details>
# 答案2
**得分**: 2
代码部分不需要翻译,以下是翻译好的部分:
问题出在您的代码中,因为paste0() 返回一个字符向量,例如 'var2',而不是table()函数的正确参数。您可以使用双方括号 '[[' 来提取列:
```R
# 创建一个列表以保存循环的结果
tl <- vector(mode = 'list')
# 运行循环,并将每列的结果添加到 'tl' 的相应元素中
for (i in colnames(df)[2:3]) {
tl[[i]] <- table(df[[i]], df$class)
}
# 输出
tl
或者,您可以使用lapply()函数:
lapply(df[, 2:3], function(x) table(x, df$class))
希望这对您有所帮助。
英文:
The issue with your code is that because paste0() returns a character vector e.g, 'var2' and is not a correct argument for table() function. You can use the double bracket '[[' to extract the columns:
# create a list to save the results from loop
tl<-vector(mode = 'list')
# run the loop and add the results for each column in the corresponding element of 'tl'
for (i in colnames(df)[2:3]) {
tl[[i]]<-table(df[[i]], df$class)
}
output
tl
$var2
A B
0 0 1
1 1 0
$var3
A B
0 1 0
1 0 1
alternatively you can use lapply() function:
lapply(df[, 2:3], function(x) table(x, df$class))
var2
x A B
0 0 1
1 1 0
$var3
x A B
0 1 0
1 0 1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论