Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 添加包含整型列的装箱值的列_R_R Faq - Fatal编程技术网

R 添加包含整型列的装箱值的列

R 添加包含整型列的装箱值的列,r,r-faq,R,R Faq,我有一个数据框,有几列,其中一列是秩,一个介于1和20之间的整数。我想创建另一列,其中包含一个bin值,如“1-4”、“5-10”、“11-15”、“16-20” 最有效的方法是什么 我拥有的数据帧如下所示(.csv格式): 我想在dataframe中添加另一列,如下所示: rank,name,info,binValue 1,steve,red,"1-4" 3,joe,blue,"1-4" 6,john,green, "5-10" 3,liz,yellow,"1-4" 15,jon,pink,"

我有一个数据框,有几列,其中一列是秩,一个介于1和20之间的整数。我想创建另一列,其中包含一个bin值,如“1-4”、“5-10”、“11-15”、“16-20”

最有效的方法是什么

我拥有的数据帧如下所示(.csv格式):

我想在dataframe中添加另一列,如下所示:

rank,name,info,binValue
1,steve,red,"1-4"
3,joe,blue,"1-4"
6,john,green, "5-10"
3,liz,yellow,"1-4"
15,jon,pink,"11-15"

我现在这样做的方式不起作用,因为我希望保持data.frame不变,如果df$ranged的值在给定范围内,只需添加另一列。谢谢。

请参见
?剪切
并指定
中断
(可能还有
标签


x$bin
dat我们可以使用包
cutr
中的
smart\u-cut

# devtools::install_github("moodymudskipper/cutr")
library(cutr)
使用@Andrie的样本数据:

x$bins <- smart_cut(x$rank,
                    c(1,5,11,16), 
                    labels = ~paste0(.y[1],'-',.y[2]-1), 
                    simplify = FALSE)
# rank  name   info  bins
# 1    1 steve    red   1-4
# 2    3   joe   blue   1-4
# 3    6  john  green  5-10
# 4    3   liz yellow   1-4
# 5   15   jon   pink 11-15

x$bins-Related:如何使用for-loop和assign-like函数一次性为多个列执行此操作?
dat <- "rank,name,info
1,steve,red
3,joe,blue
6,john,green
3,liz,yellow
15,jon,pink"

x <- read.table(textConnection(dat), header=TRUE, sep=",", stringsAsFactors=FALSE)
x$bins <- cut(x$rank, breaks=seq(0, 20, 5), labels=c("1-5", "6-10", "11-15", "16-20"))
x

  rank  name   info  bins
1    1 steve    red   1-5
2    3   joe   blue   1-5
3    6  john  green  6-10
4    3   liz yellow   1-5
5   15   jon   pink 11-15
# devtools::install_github("moodymudskipper/cutr")
library(cutr)
x$bins <- smart_cut(x$rank,
                    c(1,5,11,16), 
                    labels = ~paste0(.y[1],'-',.y[2]-1), 
                    simplify = FALSE)
# rank  name   info  bins
# 1    1 steve    red   1-4
# 2    3   joe   blue   1-4
# 3    6  john  green  5-10
# 4    3   liz yellow   1-4
# 5   15   jon   pink 11-15