将用逗号分隔的列值转换为R中的数字向量

时间:2018-02-06 04:05:22

标签: r dataframe vector

我有一个数据框“dfx”,如下所示。我需要将“COUNTY_ID”中的值转换为向量以提供函数。

dfx:

STATE   COUNTY_ID
KS      15,21,33,101
OH      133,51,12
TX      15,21,37,51,65

我已将STATE转换为如下矢量:

st = as.vector(as.character(dfx$STATE))

但是,我需要将"COUNTY_ID"列中的每一行转换为数字/数字向量。例如,c(15,21,33,101)

我怎样才能在R中实现这一目标?

感谢任何帮助。

cty_id <- lapply(strsplit(as.character(dfx$COUNTY_ID), ","), as.numeric)

DOES NOT work:
mclapply(cty_id[1], FUN = each_cty, st = st[1], mc.cores = detectCores() - 1) 

DOES works: 
mclapply(c(15,21,33,101), FUN = each_cty, st = st[1], mc.cores = detectCores() - 1) 

2 个答案:

答案 0 :(得分:2)

这是你之后的事吗?

enum ConstructorType {
 GOAL,
 GAME
}

public Player(int value, ValueType type)
{
    switch(type){
      case GOAL:
goals = value;
        break;
      case GAME:
games = value;
         break;
default:
break;
    }
this(games, goals, 0, 'X'); // Prefer this one instead of repeat your constructor code.
}

说明:public Player(int initialGoals, int initialGames) { this(initialGames, initialGoals, 0, 'X'); } 根据strsplit(as.character(dfx$COUNTY_ID), ",") #[[1]] #[1] "15" "21" "33" "101" # #[[2]] #[1] "133" "51" "12" # #[[3]] #[1] "15" "21" "37" "51" "65" 拆分每个条目,并将结果存储在strsplit(..., ",")个字符向量中。

或者获得","数字向量:

list

答案 1 :(得分:0)

当KS有四个不同的county_id值时,你想如何处理示例数据中的情况,但OH只有三个?如果你试图为每个county_id获得一列,并且你可以在某些单元格中缺少值,那么最简单的方法就是使用stringr::str_split_fixed()

> result <- stringr::str_split_fixed(dfx$COUNTY_ID, ",", n=5)
> result 
    [,1]  [,2] [,3] [,4]  [,5]
[1,] "15"  "21" "33" "101" ""  
[2,] "133" "51" "12" ""    ""  
[3,] "15"  "21" "37" "51"  "65"

请注意,您需要知道每行的最大县数数量,并将其作为参数n放在上面。你可以保守,只需稍后删除满载NA的列。

你从中得到的是一个字符矩阵。然后,您可以将其转换为数字,如下所示:class(result) <- 'numeric'。之后,result矩阵的每一行都会为您提供感兴趣的向量,您可能需要将其包含在na.omit()中,以确保只获得数字。