首页 > 解决方案 > 替换特定字符并除以余数

问题描述

我有以下示例数据框:

Date <- c("2013-01-01","2013-01-10","2013-01-16","2013-01-19")
concentration1 <- c("12","<10","<2","14")
concentration2 <- c("10","<10","<5","15")
y <- data.frame(Date, concentration1,concentration2)
y$Date <- as.Date(y$Date)

我需要在数据框中搜索“<”符号,将其删除并将余数除以 2。我试图使用以下代码获得结果:

y <- data.frame(lapply(y, function(x) {
  gsub("<", "", x)
 }))

但是,我无法将余数除以 2。

更新:

这是我的原始代码,其中包含基于@RHertel 回复的数据:

hw13<-read.csv("https://www.dropbox.com/s/dw6fket1b0bmoll/HW2013_%20Doemitz.csv?dl=1",sep=";",header=TRUE)

hw13$Datum<-as.Date(hw13$Datum, format="%d.%m.%Y")#convert to date
hw13[] <- lapply(hw13, as.character)     
hw13[sapply(hw13, startsWith, "<")] <- as.numeric(substring(hw13[sapply(hw13, startsWith, "<")],2)) / 2

标签: r

解决方案


y[2:3] <- lapply(y[2:3],function(x){
  x <- as.character(x) # if it's a factor
  flag    <- startsWith(x,"<")
  x       <- as.numeric(gsub("^<","",x))
  x[flag] <- x[flag] / 2
  x
})

#          Date concentration1 concentration2
# 1 2013-01-01             12           10.0
# 2 2013-01-10              5            5.0
# 3 2013-01-16              1            2.5
# 4 2013-01-19             14           15.0

推荐阅读