2017-10-11 74 views
1

這是一個基本問題,我很尷尬地問。將分隔字符串轉換爲數據框中的數字向量

比方說,我有一個數據幀完全包含以下形式的數據列:

test <-"3000,9843,9291,2161,3458,2347,22925,55836,2890,2824,2848,2805,2808,2775,2760,2706,2727,2688,2727,2658,2654,2588" 

我想將其轉換爲數字向量,這是我喜歡這樣做:

test <- as.numeric(unlist(strsplit(test, split=","))) 

我現在要包含這個充滿數據的列到一個數值向量當量的大數據幀轉換:

mutate(data, 
    converted = as.numeric(unlist(strsplit(badColumn, split=","))), 
) 

因爲那時它轉換整列到一個數值向量,然後用該值替代單行這不起作用:

Error in mutate_impl(.data, dots) : Column converted must be length 20 (the number of rows) or one, not 1274

我該怎麼辦呢?

+0

分割後該列太長。它看起來像你的數據只有20行,但拆分列有1274個元素。如果你不想把它作爲數據中的新列(這是mutate的作用),你可以使用'as.numeric(unlist(strsplit(data $ badColumn,split =「,」)))' –

+0

我明白,但我很困惑,爲什麼是這樣。當前行包含「10,20,30,40」等值,我只是希望將這些值替換爲相當於c(10,20,30,40)的數字向量。 – Parseltongue

+0

所以你想在給定的行中有多個數值?例如。第1行可能有'c(10,20,30)'? –

回答

1

下面是重現你的錯誤一些示例數據:

data <- data.frame(a = 1:3, 
        badColumn = c("10,20,30,40,50", "1,2,3,4,5,6", "9,8,7,6,5,4,3"), 
        stringsAsFactors = FALSE) 

這裏的錯誤:

library(tidyverse) 
mutate(data, converted = as.numeric(unlist(strsplit(badColumn, split=",")))) 
# Error in mutate_impl(.data, dots) : 
# Column `converted` must be length 3 (the number of rows) or one, not 18 

一個簡單的方法是隻使用strsplit對整列,並lapply ... as.numeric將結果列表值從字符向量轉換爲數字向量。

x <- mutate(data, converted = lapply(strsplit(badColumn, ",", TRUE), as.numeric)) 
str(x) 
# 'data.frame': 3 obs. of 3 variables: 
# $ a  : int 1 2 3 
# $ badColumn: chr "10,20,30,40,50" "1,2,3,4,5,6" "9,8,7,6,5,4,3" 
# $ converted:List of 3 
# ..$ : num 10 20 30 40 50 
# ..$ : num 1 2 3 4 5 6 
# ..$ : num 9 8 7 6 5 4 3 
1

基礎R

A=c(as.numeric(strsplit(test,',')[[1]])) 

A 
[1] 3000 9843 9291 2161 3458 2347 22925 55836 2890 2824 2848 2805 2808 2775 2760 2706 2727 2688 2727 2658 2654 2588 


df$NEw2=lapply(df$NEw, function(x) c(as.numeric(strsplit(x,',')[[1]]))) 

df%>%mutate(NEw2=list(c(as.numeric(strsplit(NEw,',')[[1]])))) 
+0

這只是複製我已經在上面的功能。我的問題是物理替換數據框中的列(它當前包含字符串)與數字向量等效 – Parseltongue

+0

@Parseltongue檢查更新 – Wen

2

這可能幫助:

library(purrr) 

mutate(data, converted = map(badColumn, function(txt) as.numeric(unlist(strsplit(txt, split = ","))))) 

你得到的是一個列表列包含數字載體。

+0

是的,你是對的。我編輯了我的答案。 – kath

+0

這是一個很好的答案 - 謝謝kath。我接受A5s的答案,因爲它讓我更清楚一點 – Parseltongue

相關問題