I want to create a vector of counts in the following way:
say my vector is
x <- c(1,1,1,1,2)
Run Code Online (Sandbox Code Playgroud)
which represents a categorical variable. I want a second vector of the form
x1 <- c(4,4,4,4,1)
Run Code Online (Sandbox Code Playgroud)
which represents the count at each level. e.g. 4 occurrences of level 1, and 1 occurrence of level 2.
I have tried
r <- range(x) ; table(factor(x, levels = r[1]:r[2]))
tabulate(factor(x, levels = min(x):max(x)))
table(x)
Run Code Online (Sandbox Code Playgroud) 我想确定两个矩阵在同一位置是否具有NA。
设置:我们有三个矩阵。我想运行一个函数,告诉我mat1和mat2在相同位置具有NA,并且告诉我mat1(和mat3)与mat2在不同位置具有NA
mat1 <- matrix(nrow=2, ncol =2, data =c(NA,0,0,NA))
mat2 <- matrix(nrow=2, ncol =2, data=c(NA,0,0,NA))
mat3 <- matrix(nrow=2, ncol=2, data = c(NA,0,0,0))
Run Code Online (Sandbox Code Playgroud) 按月划分的子集数据仅包括3月,6月,9月和12月。
设定:
x1 <- rnorm(24,0,1)
x2 <- rnorm(24,0,1)
x3 <- rnorm(24,0,1)
mat1 <- data.frame(rbind(x1,x2,x3))
colnames(mat1) <- c("Jan.96", "Feb.96", "Mar.96", "Apr.96", "May.96", "Jun.96", "Jul.96", "Aug.96", "Sep.96", "Oct.96", "Nov.96", "Dec.96", "Jan.97", "Feb.97", "Mar.97", "Apr.97", "May.97", "Jun.97", "Jul.97", "Aug.97", "Sep.97", "Oct.97", "Nov.97", "Dec.97")
Run Code Online (Sandbox Code Playgroud)
我希望最终矩阵只包含名称包含“ Mar”,“ Jun”,“ Sep”,“ Dec”的列。输出应采用以下形式:
output <- cbind(mat1$Mar.96, mat1$Jun.96, mat1$Sep.96, mat1$Dec.96, mat1$Mar.97, mat1$Jun.97, mat1$Sep.97, mat1$Dec.97)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 0.5179178 -0.4810577 0.2178482 -0.4867642 -0.1219542 0.3185248 1.464423 0.4775712
[2,] 0.4905709 1.2061020 -0.6434293 -0.1864487 -0.2297027 -0.3290413 -3.438259 …Run Code Online (Sandbox Code Playgroud)