R:在数据框中将分数转换为小数 [英] R: converting fractions into decimals in a data frame
问题描述
我正在尝试将以小数形式存储为字符的数字的数据帧转换为以十进制形式存储为数字的数据.(还有一些整数,也存储为char.)我想保留数据帧的当前结构,即,我不想作为结果的列表.
I am trying to convert a data frame of numbers stored as characters in a fraction form to be stored as numbers in decimal form. (There are also some integers, also stored as char.) I want to keep the current structure of the data frame, i.e. I do not want a list as a result.
示例数据帧(请注意:实际数据帧具有所有元素作为字符,这是一个因素,但我无法弄清楚如何使用字符复制数据帧):
Example data frame (note: the real data frame has all elements as character, here it is a factor but I couldn't figure out how to replicate a data frame with characters):
a <- c("1","1/2","2")
b <- c("5/2","3","7/2")
c <- c("4","9/2","5")
df <- data.frame(a,b,c)
我尝试了 df []<-apply(df,1,function(x)eval(parse(text = x)))
.这样可以正确计算数字,但只计算最后一列,以此填充数据框.
I tried df[] <- apply(df,1, function(x) eval(parse(text=x)))
. This calculates the numbers correctly, but only for the last column, populating the data frame with that.
结果:
a b c
1 4 4.5 5
2 4 4.5 5
3 4 4.5 5
我还尝试了 df []<-lapply(df,function(x)eval(parse(text = x)))
,其结果如下(我也不知道为什么):
I also tried df[] <- lapply(df, function(x) eval(parse(text=x)))
, which had the following result (and I have no idea why):
a b c
1 3 3 2
2 3 3 2
3 3 3 2
所需结果:
a b c
1 1 2.5 4
2 0.5 3 4.5
3 2 3.5 5
非常感谢!
推荐答案
您可能正在寻找:
df[] <- apply(df, c(1, 2), function(x) eval(parse(text = x)))
df
a b c
1 1.0 2.5 4.0
2 0.5 3.0 4.5
3 2.0 3.5 5.0
eval(parse(text = x))
一次评估一个表达式,因此,您需要一个接一个地运行一个单元格.
evaluates one expression at a time so, you need to run cell by cell.
如果无法评估某些数据框元素,则可以通过在函数内添加ifelse语句来解决这一问题:
if some data frame elements can not be evaluated you can account for that by adding an ifelse statement inside the function:
df[] <- apply(df, c(1, 2), function(x) if(x %in% skip){NA} else {eval(parse(text = x))})
跳过是元素的向量,不应该求值.
Where skip is a vector of element that should not be evaluated.
这篇关于R:在数据框中将分数转换为小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!