[英]how to store the printed output from a function as a vector in R?
我有一个dataframe
以下列
df <- data.frame(
crime = as.character(c(115400, 171200, 91124, 263899, 67601, 51322)),
stringsAsFactors=FALSE
)
我正在使用一个函数根据某些条件提取前两位数字,如下面的函数所示
for (i in df$crime){
if (nchar(i)==6){
print(substring(i,1,2))}
else {print(substring(i,1,1))
}
}
当我运行这个函数时,我得到以下输出,这是我想要的
[1] "11"
[1] "17"
[1] "9"
[1] "26"
[1] "6"
[1] "5"
但是,我希望将其保存为沿矢量。 我怎么做?
这是一个带有ifelse
+ substring
的基本 R 解决方案
res <- with(df, substring(crime,1,ifelse(nchar(crime) == 6, 2, 1)))
以至于
> res
[1] "11" "17" "9" "26" "6" "5"
substr/substring
是矢量化的,所以我们可以使用ifelse
v1 <- with(df1, ifelse(nchar(crime) == 6, substr(crime, 1, 2), substr(crime, 1, 1)))
v1
#[1] "11" "17" "9" "26" "6" "5"
在 OP 的 for 循环中,可以初始化一个vector
来存储每次迭代中的输出
v1 <- character(nrow(df1))
for (i in seq_along(df1$crime)){
if (nchar(df1$crime[i])==6){
v1[i] <- substring(df1$crime[i],1,2)
} else {
v1[i] <- substring(df1$crime[i],1,1)
}
}
使用正则表达式:
output <- with(df, ifelse(nchar(crime) == 6, sub("(..).*", "\\1", crime),
sub("(.).*", "\\1", crime)))
output
#[1] "11" "17" "9" "26" "6" "5"
使用str_extract
from stringr
变得更简单
with(df, ifelse(nchar(crime) == 6, stringr::str_extract(crime, ".."),
stringr::str_extract(crime, ".")))
我可以想象在某些情况下将提取的代码保留在原始数据框中是有用的。
我将使用data.table
包,因为它速度很快,如果您的数据很大,这可能会很方便。
library(data.table)
# convert your data.frame to data.table
setDT(df)
# filter the rows where crime length is 6,
# and assign the first two characters of
# it into a new variable "extracted".
# some rows now have NAs in the new
# field. The last [] prints it to screen.
df[nchar(crime) == 6, extracted := substring(crime, 1, 2)][]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.