用拆分字符串创建整数

时间:2017-03-24 14:23:03

标签: r string merge split numbers

我尝试使用merge:

budget = sapply(budget1, function(i) {
    Reduce(merge,budget1)[[i]]
    }
    )

并获取错误budget1 [[i]]中的错误:在第1级没有此类索引

问题是我无法找到解决以下问题的方法,有人知道处理这些数据的方法吗?

我想在数据框中添加一个列,其中包含仍在以下列表中拆分的数字:

> budget1
[[1]]
[1] "4"   "000" "000"

[[2]]
character(0)

[[3]]
character(0)

[[4]]
[1] "30"  "000" "000"

[[5]]
[1] "20"  "000" "000"

[[6]]
character(0)

[[7]]
character(0)

[[8]]
character(0)

[[9]]
[1] "22"  "500" "000"

[[10]]
[1] "0"

[[11]]
[1] "4"   "635" "000"

[[12]]
[1] "12"  "000" "000"

[[13]]
character(0)

[[14]]
[1] "9"   "000" "000"

[[15]]
character(0)

[[16]]
character(0)

[[17]]
[1] "18"   "745"  "17"   "2017"

[[18]]
[1] "0"

[[19]]
[1] "47"  "000" "000"

[[20]]
character(0)

1 个答案:

答案 0 :(得分:2)

试试这个:

# Your list
budget1 <- list(c("4", "000", "000"),
                character(0), 
                character(0),
                c("18", "745", "17", "2017"),
                c("0"))


#Create toy dataframe
mydataframe <- data.frame(a = 1:length(budget1))


# Add new column "budget" to our dataframe, containing the elements of budget1 as numeric values 

mydataframe$budget <- as.numeric(lapply(budget1, paste, collapse =""))

结果:

mydataframe$budget

[1]     4000000          NA          NA
[4] 18745172017           0

class(mydataframe$budget)
[1] "numeric"