求R中两列的和

tzdcorbm  于 2023-05-04  发布在  其他
关注(0)|答案(8)|浏览(158)

我觉得有点尴尬,因为我试图在R中添加两列以获得产品。
我试过了

sum(col1,col2)

但这个又回来了

Error in Summary.factor(c(49L, 48L, 47L, 46L, 46L, 45L, 45L, 44L, 43L,  : 
  sum not meaningful for factors

我以为这会很简单!两列都包含整数。

f4t66c6m

f4t66c6m1#

sum函数将所有数字相加,生成一个数字,而不是一个向量(至少不是长度大于1的向量)。
看起来至少有一个列是一个因素。您可以通过检查以下内容将它们转换为数值向量

head(as.numeric(data$col1))  # make sure this gives you the right output

如果这看起来是对的

data$col1 <- as.numeric(data$col1)
data$col2 <- as.numeric(data$col2)

您可能必须先将它们转换为字符。在这种情况下

data$col1 <- as.numeric(as.character(data$col1))
data$col2 <- as.numeric(as.character(data$col2))

如果无法看到数据,很难判断应该执行哪一项操作。
一旦列是数字,你只需要做

data$col3 <- data$col1 + data$col2
mpbci0fu

mpbci0fu2#

tablename$column3=rowSums(cbind(tablename$column1,tablename$column2),na.rm=TRUE)

这可用于忽略Excel工作表中的空白值。
我使用的是Euro stat数据集。
这个例子在R中运行:

crime_stat_data$All_theft <-rowSums(cbind(crime_stat_data$Theft,crime_stat_data$Theft_of_a_motorised_land_vehicle, crime_stat_data$Burglary, crime_stat_data$Burglary_of_private_residential_premises), na.rm=TRUE)
gorkyyrv

gorkyyrv3#

你可以使用for循环:

for (i in 1:nrow(df)) {
   df$col3[i] <- df$col1[i] + df$col2[i]
}
q1qsirdb

q1qsirdb4#

第一种方式

df$New1 <- df$X1+df$X2+df$X3

第二种方式

df <-df %>% select(contains('X')) %>% mutate(New2=rowSums(.))
shstlldc

shstlldc5#

可能有一两个列中包含因子,或者更有可能的是,您的列可能被格式化为因子。请尝试给予str(col1)和str(col2)。这应该可以告诉您这些列的格式。
我不确定你是想把一列的行加起来生成一个新列,还是只是把两列中的所有数字都加起来得到一个数字。

ekqde3dh

ekqde3dh6#

你可以这样做:

df <- data.frame("a" = c(1,2,3,4), "b" = c(4,3,2,1), "x_ind" = c(1,0,1,1), "y_ind" = c(0,0,1,1), "z_ind" = c(0,1,1,1) )
df %>% mutate( bi  = ifelse((df$x_ind + df$y_ind +df$z_ind)== 3, 1,0 ))
mspsb9vt

mspsb9vt7#

df$row_sums <- 0
# Loop over each row
for (i in 1:nrow(df)) {
  # Sum the values in each row starting from the second column
  row_sum <- sum(df[i, 2:ncol(df)])
  
  # Assign the row sum to the new column
  df$row_sums[i] <- row_sum
}
# Add up the row sums to get the total sum of all row sums
total_row_sum <- sum(df$row_sums)

# Print the total sum of all row sums
cat("The total sum of all row sums is:", total_row_sum, "\n")
ejk8hzay

ejk8hzay8#

尝试将column3创建为表中column1 + column2的总和

tablename$column3=rowSums(cbind(tablename$column1,tablename$column2))

相关问题