有条件地从现有列创建新列(Create new columns from an existing column conditionally)

编程入门 行业动态 更新时间:2024-10-21 05:53:58
有条件地从现有列创建新列(Create new columns from an existing column conditionally)

我试图有条件地从一列数据生成值,有条件地基于其中一列中的值。

fio2 <- c(0.25, 0.5, 0.8) pao2 <- c(100, 60, 90) paco2 <- c(35, 45, 45) df <- data.frame(fio2, pao2, paco2)

如果fio2 <0.5,我希望将同一行中相应的pao2值复制到新列(pao2_raw)中。 如果fio2> = 0.5我想执行一个使用行中其他值的函数,然后将它存储在一个新列(aao2)中。 在我的实际数据中有许多数据点,相关的列分散在数据集中。 我的想法如下:

#Function for when fio2 >= 0.5 aagrad <- function(x) { (x * (705) - df$paco2/0.8) - df$pao2 } #Sorting function aasort <- function(x) { if (x < 0.5) { df$pao2_raw <- df$pao2 } else { aao2 <- aagrad(x) } } #run function sapply(df$fio2, aasort(df$fio2))

预期输出为df $ pao2_raw,其值为(100,NA,NA) - 直接从$ pao2移动,df $ aao2(NA,236.25,417.75)是使用aagrad函数计算的。

我对如何修复aasort的语法没有任何线索,而且我对使用sapply实际将条件操作应用于整个列完全没有信心。 非常感谢协助。

I am trying to conditionally generate values from a columns of data, conditionally based on the value in one of the columns.

fio2 <- c(0.25, 0.5, 0.8) pao2 <- c(100, 60, 90) paco2 <- c(35, 45, 45) df <- data.frame(fio2, pao2, paco2)

If fio2 < 0.5 I would like the corresponding value of pao2 in the same row to be copied into a new column (pao2_raw). If fio2 >= 0.5 I would like to perform a function that uses other values in the row, then store it in a new column (aao2). In my actual data there are many data points, and the relevant columns are dispersed through the data set. My thinking is as follows:

#Function for when fio2 >= 0.5 aagrad <- function(x) { (x * (705) - df$paco2/0.8) - df$pao2 } #Sorting function aasort <- function(x) { if (x < 0.5) { df$pao2_raw <- df$pao2 } else { aao2 <- aagrad(x) } } #run function sapply(df$fio2, aasort(df$fio2))

The expected output would be a df$pao2_raw with values of (100, NA, NA) - directly moved from $pao2, and df$aao2 (NA, 236.25,417.75) which were calculated using the aagrad function.

I don't have a clue about how to fix the syntax of aasort, and I'm not at all confident about the use of sapply to actually apply the conditional manipulations to the whole of a column. And assistance would be greatly appreciated.

最满意答案

似乎可以通过常规任务和ifelse来完成:

df$pao2_raw = ifelse(df$fio2 < 0.5, df$pao2, NA) df$aao2 = ifelse(df$fio2 < 0.5, NA, aagrad(df$fio2)) df # fio2 pao2 paco2 pao2_raw aao2 # 1 0.25 100 35 100 NA # 2 0.50 60 45 NA 236.25 # 3 0.80 90 45 NA 417.75

Seems it could be done with regular assignments and ifelse:

df$pao2_raw = ifelse(df$fio2 < 0.5, df$pao2, NA) df$aao2 = ifelse(df$fio2 < 0.5, NA, aagrad(df$fio2)) df # fio2 pao2 paco2 pao2_raw aao2 # 1 0.25 100 35 100 NA # 2 0.50 60 45 NA 236.25 # 3 0.80 90 45 NA 417.75

更多推荐

本文发布于:2023-07-08 20:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1080248.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   Create   columns   conditionally   column

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!