Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.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:如何将列添加到数据矩阵中,前1599行为;红葡萄酒;接下来的5000行为;白葡萄酒;_R - Fatal编程技术网

R:如何将列添加到数据矩阵中,前1599行为;红葡萄酒;接下来的5000行为;白葡萄酒;

R:如何将列添加到数据矩阵中,前1599行为;红葡萄酒;接下来的5000行为;白葡萄酒;,r,R,我想在一个有6497行的数据矩阵中添加一个名为“Type”的列 对于列中的1到1599行,我想输入值“redwine”,对于1600到6497行,我想输入值“whitewine” 如何在R中实现此代码 非常感谢你,因为我是一个新的学习者 如果您有一个名为x的data.frame,您可以使用 x$Type <- NA x$Type[1 : 1599] <- "redwine" x$Type[1600 : 6497 ] <- "whitewine" 你好,data.frame 数

我想在一个有6497行的数据矩阵中添加一个名为“Type”的列

对于列中的1到1599行,我想输入值“redwine”,对于1600到6497行,我想输入值“whitewine”

如何在R中实现此代码


非常感谢你,因为我是一个新的学习者

如果您有一个名为x的data.frame,您可以使用

x$Type <- NA
x$Type[1 : 1599] <- "redwine"
x$Type[1600 : 6497 ] <- "whitewine"
你好,data.frame 数据框是R中问题的方便存储设备。它非常像您在问题陈述中提到的矩阵。这里有一种方法可以使用R中的
data.frame
对象来包含包含N行的1列数据

创建包含所需数据的列表
list1您也可以做
x$Type由于这个答案有效,我假设
x
是一个数据帧,而不是一个数据矩阵。它们在R中是不同的东西。
rep
也是矢量化的,所以
rep(c(“红葡萄酒”、“白葡萄酒”)、c(15996497-1599))
也可以工作。或者甚至
rep(c(“红葡萄酒”、“白葡萄酒”)、diff(c(015996497))
如果你想得到fancyI建议你也为初学者使用一些教程。不需要
列表
,然后
取消列表
-只要
c(列表1,列表2)
就可以了。
cbind(x, c(rep("redwine",1599), rep("whitewine",6497 - 1599))) 
list1 <- rep("red",1599)# replicate is build into R, it will clone the first argument, by the second argument's number of times, and return it as a list.
list2 <- rep("white", 4898)
list3 <- list(list1, list2) # this is a list object, containing 2 other lists, accessible via this notation list3[[1]] gets your red wines, and list3[[2]] gets your white wines.
list_flattened <- unlist(list3) # This turns a list of lists, into 1 list of unified items.

df <- data.frame(Type=list_flattened) # this creates a matrix like object, with a column named Type and its entries (or rows) as that big list we generated.

> head(df)# helper function to print the first 5 rows of the df
  Type
1  red
2  red
3  red
4  red
5  red
6  red
> tail(df) # helper function to print the last 5 rows of the df
      Type
6492 white
6493 white
6494 white
6495 white
6496 white
6497 white