gpt4 book ai didi

r - 给定条件强制字符串的函数

转载 作者:行者123 更新时间:2023-12-04 02:25:17 25 4
gpt4 key购买 nike

我只是想强制转换为数字——即,将 as.numeric 应用于任何以 1 作为第一个条目的列(即,一个特点)。所以我希望转:

tibble(a = c("1", "2"), b = c("Fred", "Kevin"), c = 1:2)

进入

tibble(a = 1:2, b = c("Fred", "Kevin"), c = 1:2)

最佳答案

你可以使用dplyr:

library(dplyr)

data %>%
mutate(across(where(~ first(.x) == "1" & !is.na(first(.x))), as.numeric)).

返回

# A tibble: 2 x 5
a b c d e
<dbl> <chr> <dbl> <dbl> <lgl>
1 1 Fred 1 1 NA
2 2 Kevin 2 3 NA

数据

data <- tibble(a = c("1", "2"), 
b = c("Fred", "Kevin"),
c = 1:2,
d = c("1", "3"),
e = c(NA, NA))

关于r - 给定条件强制字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68247154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com