【问题标题】:How Can I Turn 120/80 into Two Columns (120 and 80)?如何将 120/80 变成两列(120 和 80)?
【发布时间】:2020-12-19 06:39:02
【问题描述】:

我有一列读作###/##的血压,我要做的就是将分子夹在一个列中,将分母夹在另一列中。

请帮忙?

【问题讨论】:

  • tidyr::separate(df, first_bp, into = c("Systolic", "Diastolic"), sep = "/" , convert = T) 可以

标签: r dplyr


【解决方案1】:
library(dplyr)
library(stringr)

df = data.frame(
first_bp = c("120/80","90/60"),
id = c("0001234","0001235"),
amount = c(18.50, -18.50), stringsAsFactors = F)
  
 
df %>%  
mutate(s0 = str_split(first_bp,"/")) %>%
rowwise() %>%
mutate(systole = as.numeric(s0[1]), 
       diastole = as.numeric(s0[2])) %>%
select(first_bp, id, amount, systole, diastole)

【讨论】:

  • 谢谢!
    所以我的df中的变量叫做first_bp,当我这样做时\ mutate(s0 = str_split(first_bp,"/"), systole = as.numeric(s0[[1]]), diastole = as .nu​​meric(s0[[2]])) %>% select(first_bp, systole, diastole)\ 我收到错误消息“错误:无效索引:超出范围”\ 我会做一个 reprex,我知道每个人都说这很容易做到,但我发誓这需要我永远......
  • 我的意思是看,我什至不知道如何创建一个新行。为什么

    不起作用?!?

  • 库(tidyverse)库(stringr)库(tibble)tibble::tribble(~first_bp,~id,~ammount,“120/80”,“0001234”,“$18.50”,“90 /60"、"0001235"、"-$18.50") %>% 变异(s0 = str_split(first_bp,"/")、systole = as.numeric(s0[[1]])、diastole = as.numeric(s0 [[2]])) %>% select(first_bp, systole, diastole) #> # A tibble: 2 x 3 #> first_bp systole diastole #> #> 1 120/80 120 90 #> 2 90/60 80 60
  • 请查看上述是否有效,使用最新数据的数据框进行编辑。
【解决方案2】:

您可以使用.split() 函数来做到这一点。

以下是执行此操作的示例:

blood_pressure = '120/80'
blood_pressure = blood_pressure.split('/')

numerator = blood_pressure[0]
denominator = blood_pressure[1]

print(numerator, denominator)

输出:

120 80

【讨论】:

    猜你喜欢
    • 2014-11-28
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多