I have a character column called ipaq_2 in r that is like "02:00" (hour:minute). Also the column has some NA values. I need to convert this column into a numeric column that shows the minutes (in the above example: 120), replacing at the same time NA values with the mean. enter image description here

推荐答案

可以使用lubridate::hm将字符列转换为小时和分钟,然后将值转换为分钟.然后,我们可以用分钟列的平均值替换任何NA个值.

library(lubridate)
df <- data.frame(ipaq_2 = c("1:00", "0:45", "0:30", "1:30", NA))

df$ipaq_2 <- hm(df$ipaq_2, quiet = TRUE)        # format to 'hours:minutes:seconds'

df$minutes <- hour(df$ipaq_2)*60 + minute(df$ipaq_2)

df$minutes[is.na(df$minutes)] <- mean(df$minutes, na.rm = TRUE)

或者另一种可能性(感谢@Ben):

df$minutes <- as.numeric(hm(df$ipaq_2, quiet = T))/60
df$minutes[is.na(df$minutes)] <- mean(df$minutes, na.rm = TRUE)

或与tidyverse:

library(tidyverse)
library(lubridate)

df %>% 
  mutate(ipaq_2 = hm(ipaq_2, quiet = TRUE),
         minutes = hour(ipaq_2)*60 + minute(ipaq_2),
         minutes = ifelse(is.na(minutes), mean(minutes, na.rm = TRUE), minutes))

# Or using the alternative above:
# df %>%
#   mutate(minutes = as.numeric(hm(ipaq_2, quiet = T))/60,
#          minutes = ifelse(is.na(minutes), mean(minutes, na.rm = TRUE), minutes))

Output

     ipaq_2 minutes
1  1H 0M 0S   60.00
2    45M 0S   45.00
3    30M 0S   30.00
4 1H 30M 0S   90.00
5      <NA>   56.25

R相关问答推荐

用apply/map/etch替换循环以加快速度

如何在热图中绘制一个图形,但在每个单元格中通过饼形图显示?

卸载安装了BRM的模型发出的警告

无法运行通过R中的Auto.arima获得的ARIMA模型

在另一个函数中调用ggplot2美学

删除列表中存储的数据帧内和数据帧之间的重复行

单个轮廓重叠条的单独图例

如何根据R中其他列的值有条件地从列中提取数据?

在连续尺度上转置标签[瀑布图,R]

在R中,如何将变量(A,B和C)拟合在同一列中,如A和B,以及A和C在同一面板中?

多个过滤器内的一个盒子在仪表板Quarto

移除仪表板Quarto中顶盖和车身之间的白色区域

DEN扩展包中的RECT树形图出现异常行为

如何在R中使用hmm TMB提前一步预测观察到的状态?

如何删除R中除数字元素以外的所有元素

`-`是否也用于数据帧,有时使用引用调用?

使用ifElse语句在ggploy中设置aes y值

如何将EC50值绘制在R中的剂量-react 曲线上?

Ggplot2如何找到存储在对象中的残差和拟合值?

如何使用循环从R中的聚合函数创建列,而不会在名称中给出&q;$&q;?