我这里有一个数据框,想创建一个新列,它是一列除以另一列的商。
首先,我尝试:
df$new_column_name <- df$dividend column / df$divisor column
当我以这种方式格式化它时,我收到错误:
"错误:df$股息列/df$除数列中出现意外符号"
我也尝试过:
df$new_column_name <- df$"dividend column" / df$"divisor column"
在这里我得到了错误:
"二元运算符的非数字参数"
用于数学的两列在名称中都有空格,如果这有所不同的话。
正如joran在评论中提到的,在列名中使用空格确实是不明智的。这会导致很多麻烦。听起来你的列不是数字的。你可以使用str
来查看你拥有的列的类型。下面是一个例子,使用tidyverse包可能解决你的问题,我强烈建议你去看看。
library(tidyverse)
# create data frame with space in column names
df <- data.frame("dividend column" = 1:5, "divisor column" = 6:10, check.names = FALSE)
# use str to get the classes of each column
str(df)
#> 'data.frame': 5 obs. of 2 variables:
#> $ dividend column: int 1 2 3 4 5
#> $ divisor column : int 6 7 8 9 10
# use set_tidy_names to replace space in column names with '.'
# change columns to numeric values
# use dplyr::mutate to create the new column
df <- set_tidy_names(df, syntactic = TRUE) %>%
mutate_at(vars(c("dividend.column", "divisor.column")), as.numeric) %>%
mutate(new_column_name = dividend.column/divisor.column)
#> New names:
#> dividend column -> dividend.column
#> divisor column -> divisor.column