简体   繁体   English

如何将范围因子拆分为R中的数字列表

[英]How To Split A Range Factor Into List Of Numbers In R

I have a factor variable in a data frame of the form 735-739 . 我在格式735-739的数据框中有一个因子变量。

I want to add this as three numeric columns (min, mean, max) to my data frame. 我想将此作为三个数字列(min, mean, max)到我的数据框中。

I'm starting by using strsplit : 我首先使用strsplit

values = sapply(range, function(r) {
    values = c(strsplit(as.character(r), "-"))
})

I get back a value of class list of length 1: 我得到一个长度为1的类list的值:

[1] "735" "739"

I'm at a loss on what my next step should be. 我不知道下一步应该做什么。 I'd appreciate a hint. 我会很高兴的提示。

There are several ways you can do this. 有几种方法可以做到这一点。 Here is one starting with concat.split.multiple from my "splitstackshape" package: 这是我的“ splitstackshape”包中以concat.split.multiple开头的一个:

## SAMPLE DATA
mydf <- data.frame(ID = LETTERS[1:3], vals = c("700-800", "600-750", "100-220"))
mydf
#   ID    vals
# 1  A 700-800
# 2  B 600-750
# 3  C 100-220

First, split the "vals" column, rename them if required (using setnames ), and add a new column with the rowMeans . 首先,拆分“丘壑”一栏,如果(使用需要重命名这些setnames ),并与添加新列rowMeans

library(splitstackshape)

mydf <- concat.split.multiple(mydf, "vals", "-")
setnames(mydf, c("vals_1", "vals_2"), c("min", "max"))
mydf$mean <- rowMeans(mydf[c("min", "max")])
mydf
#   ID min max mean
# 1  A 700 800  750
# 2  B 600 750  675
# 3  C 100 220  160

For reference, here's a more "by-hand" approach: 供参考,这是一种更“手工”的方法:

mydf <- data.frame(ID = LETTERS[1:3], vals = c("700-800", "600-750", "100-220"))
SplitVals <- sapply(sapply(mydf$vals, function(x) 
  strsplit(as.character(x), "-")), function(x) {
    x <- as.numeric(x)
    c(min = x[1], mean = mean(x), max = x[2])
  })
cbind(mydf, t(SplitVals))
#   ID    vals min mean max
# 1  A 700-800 700  750 800
# 2  B 600-750 600  675 750
# 3  C 100-220 100  160 220

Using @AnandraMahto's dataset, you could also use the data.table library - 使用@AnandraMahto的数据集,您还可以使用data.table库-

library(data.table)
dt <- data.table(ID = LETTERS[1:3], vals = c("700-800", "600-750", "100-220"))

# adding the min and max columns
splitlist <- strsplit(dt[,vals],"-")
dt[, minv := as.numeric(sapply(X = splitlist, function(x) x[1]))]
dt[, maxv := as.numeric(sapply(X = splitlist, function(x) x[2]))]

#adding mean
dt[,meanv := mean(minv:maxv), by = "vals"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM