【问题标题】:R Divide all rows of a dataframe column by a number [duplicate]R将数据框列的所有行除以一个数字[重复]
【发布时间】:2018-04-18 15:07:26
【问题描述】:

我正在尝试将我的数据框列的所有行除以一个数字(比如 10)。在我尝试之前,我认为这是一个微不足道的问题。在下面的示例中,我试图让“mm”列产生值 8100、3222.2 和 5433.3

test <- data.frame(locations=c("81000","32222","54333"), value=c(87,54,43))
test$mm <- as.numeric(test$locations) / 10
head(test)
     locations value  mm
   1     81000    87 0.3
   2     32222    54 0.1
   3     54333    43 0.2

我做错了什么?

【问题讨论】:

  • locations 不是数字,是字符,去掉逗号
  • 要么在data.frame 中指定stringsAsFactors = FALSE,要么不引用locations(例如locations=c(81000,32222,54333)),或者查看欺骗目标

标签: r dataframe divide


【解决方案1】:

factors改为character,然后应用as.numeric

> test$mm <- as.numeric(as.character(test$locations)) / 10
> test
  locations value     mm
1     81000    87 8100.0
2     32222    54 3222.2
3     54333    43 5433.3

【讨论】:

  • 感谢您的回复。有用。我没有意识到我的专栏是一个因素而不是一个角色。我会接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 2023-01-20
  • 1970-01-01
  • 2016-08-02
  • 2019-04-22
  • 2019-12-01
  • 1970-01-01
相关资源
最近更新 更多