R:在数据框中将分数转换为小数 [英] R: converting fractions into decimals in a data frame

查看:46
本文介绍了R:在数据框中将分数转换为小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个以分数形式存储为字符的数字数据帧转换为以十进制形式存储为数字.(还有一些整数,也存储为字符.)我想保留数据框的当前结构,即我不想要一个列表作为结果.

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))}) 

其中,skip 是不应计算的元素向量.

Where skip is a vector of element that should not be evaluated.

这篇关于R:在数据框中将分数转换为小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆