【问题标题】:How to remove % sign from end of number in dataframe in R如何从 R 中的数据框中的数字末尾删除 % 符号
【发布时间】:2022-11-30 04:31:09
【问题描述】:

我想知道如何找到以 % 结尾的元素并从这些元素中删除 % 符号?

data <- read.table(text="
COURSE          CLASE  GROUP_A   GROUP_B
algebra         1         25%        8%
algebra         2         35%        9%
number_theory   3         18%        7%
number_theory   4         14%        11%
math_games      5         12%        5%
math_games      6         19%        4%
",h=TRUE)

【问题讨论】:

  • str_remove_all(data$GROUP_A, "%")
  • 可以做data[] &lt;- lapply(data, function(x) sub('%$', '', x))
  • @MartinGal,谢谢,但是对于以 % 结尾的任何变量,是否有循环来执行此操作?

标签: r dataframe dplyr stringr


【解决方案1】:

此代码替换每一列中的所有“%”字符,您可以指定列。

mydata <- read.table(text="
COURSE          CLASE  GROUP_A   GROUP_B
algebra         1         25%        8%
algebra         2         35%        9%
number_theory   3         18%        7%
number_theory   4         14%        11%
math_games      5         12%        5%
math_games      6         19%        4%
",h=TRUE)
mydata[] <- lapply(mydata, function(x) gsub("%$","",x))

只是一个建议,我不会使用数据作为表名,因为它是 R 中定义的函数。

【讨论】:

  • 谢谢,但输出不是数字,仍然是字符
【解决方案2】:

lapply 在列上删除末尾的任何 % ,然后将数据框中的类型转换为数字(如果它们应该是数字)。

data |>
  replace(TRUE, lapply(data, sub, pattern = "%$", replacement = "")) |>
  type.convert(as.is = TRUE)

给予:

         COURSE CLASE GROUP_A GROUP_B
1       algebra     1      25       8
2       algebra     2      35       9
3 number_theory     3      18       7
4 number_theory     4      14      11
5    math_games     5      12       5
6    math_games     6      19       4

【讨论】:

    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    相关资源
    最近更新 更多