[英]How can I convert a non-numeric variable column into two numeric variable columns?
使用 R,我需要幫助將非數字列轉換為兩個數字列。 我想拆分 x 列中的非數字數據,破折號之前的值進入一列(開始),破折號之后的值進入另一列(結束)。 然后,我想創建一個新的數字列,其中包含 Start 和 End 列之間的差異,差異中添加了 1。 (Diff 列包含年份計數,因此從 2011 年到 2018 年將是八年。)
當我嘗試這樣做時,我遇到了意想不到的問題。 首先,x 變量顯示為一個因子。 其次,開始和結束列中的數據不是數字,當我嘗試將它們設為數字以便可以進行 Diff 計算時,我得到了一個強制錯誤。 第三,我無法讓 strsplit 工作。
我檢查了 stackoverflow 解決方案是否存在類似問題,但無法找到一個對我有用的解決方案。
輸入數據只是實際文件中的一小部分樣本
我更喜歡使用 dplyr 的解決方案,但對其他解決方案持開放態度。
輸入
dput(df)
structure(list(x = c(NA, "1950-1960", "1975-1986", "2011-2018"
)), class = "data.frame", row.names = c(NA, -4L))
Output
x Start End Diff
1950-1960 1950 1960 11
1975-1986 1975 1986 12
2011-2018 2011 2018 8
df$Start = as.numeric(unlist(lapply(strsplit(df$x, "-"), `[`, 1)))
df$End = as.numeric(unlist(lapply(strsplit(df$x, "-"), `[`, 2)))
df$Diff = df$End - df$Start + 1
df
x Start End Diff
1 <NA> NA NA NA
2 1950-1960 1950 1960 11
3 1975-1986 1975 1986 12
4 2011-2018 2011 2018 8
G5W 非常適合基礎 R,這是一個“tidyverse”版本:
library(dplyr)
library(tidyr) # separate
df %>%
filter(!is.na(x)) %>%
tidyr::separate(x, into = c("Start", "End"), sep = "-", remove = FALSE, convert = TRUE) %>%
mutate(Diff = End - Start + 1L)
# x Start End Diff
# 1 1950-1960 1950 1960 11
# 2 1975-1986 1975 1986 12
# 3 2011-2018 2011 2018 8
一個快速但不靈活的解決方案是使用substr()
來獲取 position 的年份:
df$Start <- as.numeric(substr(df$x, 1, 4))
df$End <- as.numeric(substr(df$x, 6, 10))
df$Diff <- df$End - df$Start + 1
df[!is.na(df$Diff), ]
x Start End Diff
2 1950-1960 1950 1960 11
3 1975-1986 1975 1986 12
4 2011-2018 2011 2018 8
另一個 baseR 解決方案:
df1[, c("Start", "End")] <- do.call(rbind, strsplit(df1$x, "-"))
df1 <- transform(type.convert(df1), Diff = End - Start + 1)
結果
df1
# x Start End Diff
#1 <NA> NA NA NA
#2 1950-1960 1950 1960 11
#3 1975-1986 1975 1986 12
#4 2011-2018 2011 2018 8
數據
df1 <- structure(list(x = c(NA, "1950-1960", "1975-1986", "2011-2018"
)), class = "data.frame", row.names = c(NA, -4L))
基礎 R,易讀
#your data
x <- c("1950-1960", "1975-1986", "2011-2018")
df <- as.data.frame(x)
#code
df_list <- unlist(apply(df, MARGIN = 1, strsplit, "-"))
new_data <- matrix(df_list, ncol = 2,byrow = T)
#output
output <- cbind(df,new_data)
Output:
x 1 2
1 1950-1960 1950 1960
2 1975-1986 1975 1986
3 2011-2018 2011 2018
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.