首页 > 解决方案 > 如何将数组的字符串转换为整数数组

问题描述

我有一个字符串作为"2_5_6". 我需要将字符串中的数字作为数字

这是我尝试过的:

indices = apply(strsplit("2_5_6","_" ),2 ,FUN = as.numeric) 

但是,它抱怨:

Error in apply(strsplit("2_5_6", "_"), 2, FUN = as.numeric) : 
  dim(X) must have a positive length

我不知道我的 Margin 参数应该是什么?

最简单的解决方案是什么?

标签: r

解决方案


我们可以scan在拆分时使用转换为数字_

scan(text = "2_5_6", what = numeric(), sep="_", quiet = TRUE)
#[1] 2 5 6

或者,如果我们使用strsplit,则输出是list长度为 1 的 a。它可以是unlisted 或提取的 ( [[)

as.integer(unlist(strsplit("2_5_6", "_")))

apply期望输入有一些维度,而这里没有


推荐阅读