我有一些数据显示如下
date over bed.bath
1 2016-03-17 -0.002352941 1 bed 1 bath
2 2016-03-17 -0.035294118 1 bed 1 bath
3 2016-03-17 -0.008278717 1 bed 1 bath
4 2016-03-17 -0.008350731 1 bed 1 bath
5 2016-03-17 0.004243281 1 bed 2 bath
6 2016-03-17 0.007299270 2 bed 2 batbed.bath列是一个character。我想分别提取关于床和浴的信息。我试着拆分字符串并提取出如下的数字
getbeds <- function(x){
splits = strsplit(x," ")
return(splits[[1]][1])
}但是,当我使用df<- df%>% mutate(beds = getbeds(bed.bath))时,新列仅为1s。
date over bed.bath beds
1 2016-03-17 -0.002352941 1 bed 1 bath 1
2 2016-03-17 -0.035294118 1 bed 1 bath 1
3 2016-03-17 -0.008278717 1 bed 1 bath 1
4 2016-03-17 -0.008350731 1 bed 1 bath 1
5 2016-03-17 0.004243281 1 bed 2 bath 1
6 2016-03-17 0.007299270 2 bed 2 bath 1从我的数据框架中提取我喜欢的信息的最好方法是什么?
数据
df <- structure(list(date = structure(c(16877, 16877, 16877, 16877, 16877, 16877), class = "Date"),
over = c(-0.002352941, -0.035294118, -0.008278717, -0.008350731, 0.004243281, 0.00729927),
bed.bath = c("1 bed 1 bath", "1 bed 1 bath", "1 bed 1 bath", "1 bed 1 bath", "1 bed 2 bath", "2 bed 2 bath")),
.Names = c("date", "over", "bed.bath"),
row.names = c("1", "2", "3", "4", "5", "6"), class = "data.frame")
library('dplyr')
df %>% mutate(beds = getbeds(bed.bath))发布于 2017-03-18 19:44:34
我们可以使用来自extract的tidyr
library(tidyr)
library(dplyr)
df %>%
extract(bed.bath, into = 'beds', "(\\d+).*", remove = FALSE)或者使用base R,使用sub匹配一个或多个空格(\\s+),后面跟着字符(.*),并将其替换为空格,以便在字符串开头得到数字,并删除所有其他字符。
df$beds <- with(df, as.integer(sub("\\s+.*", "", bed.bath)))OP输出值相同的原因是它只从第一个list元素([[1]])中提取第一个观测值([[1]])
发布于 2017-03-18 20:24:39
如果还想提取浴室的数量,可以使用:
getbeds <- function(x){
splits = strsplit(x," ")
as.integer( c(splits[[1]][[1]],splits[[1]][[3]]) )
}
bed.bath <- t(sapply(df$bed.bath,getbeds))
getbeds <- function(x){
splits = strsplit(x," ")
c(splits[[1]][[1]],splits[[1]][[3]])
}
bed.bath <- t(sapply(df$bed.bath,getbeds))
df$bed <- bed.bath[,1]
df$bath <- bed.bath[,2]
df
# date over bed.bath bed bath
#1 2016-03-17 -0.002352941 1 bed 1 bath 1 1
#2 2016-03-17 -0.035294118 1 bed 1 bath 1 1
#3 2016-03-17 -0.008278717 1 bed 1 bath 1 1
#4 2016-03-17 -0.008350731 1 bed 1 bath 1 1
#5 2016-03-17 0.004243281 1 bed 2 bath 1 2https://stackoverflow.com/questions/42878925
复制相似问题