我正在尝试从数据中删除%符号,并将其转换为数字,然后对它们进行除法。这是我的数据,它的部分值以数字表示,其他部分以%表示。
我尝试了以下代码来删除%符号,然后将它们转换为数字。但是,我只想对转换后的数字进行除法。无论如何,我只能在其中带有%符号的行上检查并执行除法吗?
这是我的代码
#Reading Files
tab1_data <- read_excel("Dataset.xlsx", sheet = "tab1")
tab2_data <- read_excel("Dataset.xlsx", sheet = "tab2")
#tab1_data$new <- subset(tab1_data$`Click percent`,grep("\\%$", tab1_data$`Click percent`))
d = as.numeric(gsub("\\%", "", tab1_data$`Click percent`))
现在,此处的数字1.14000理想情况下应为0.01146,但不是。 我尝试在新列中设置%值,然后对它们执行除法。但是我无法将它们子集化。
任何人都可以提供任何替代方法来实现删除%sign并对其进行除法的最终目标。
答案 0 :(得分:2)
假设x
是您的列,
x <- c(0.02, 0.011, '1.14%', '1.309%')
然后
x[grepl('%', x)] <- as.numeric(gsub('%', '', x[grepl('%', x)])) / 100
x
#[1] "0.02" "0.011" "0.0114" "0.01309"
或
as.numeric(x)
#[1] 0.02000 0.01100 0.01140 0.01309
答案 1 :(得分:1)
{@ {1}}中使用@Sotos数据的有趣选项
readr::parse_number(x)
如果存在x <- c(0.02, 0.011, '1.14%', '1.309%')
readr::parse_number(x) / c(1, 100)[grepl("%", x) + 1]
#[1] 0.0200 0.0110 0.0114 0.0131
,则除以100;否则,除以1。