所以我正在研究这个csv文件的数据集。 MYDATA = name school total_consumption ram abc 15 ram1 abcd 16 ram2 abcde 17 ram3 abcdef 18 ram4 acb 19 ram5 acbe 20
现在我想按降序对整个数据进行排序,然后分配段,例如s1,s2等。段的no取自用户作为输入。假设用户输入2将有2个段。现在总行数除以2,然后前半部分将是第1部分,后半部分将是第2部分。
段val = 2
输出segemnt
20 s1
19 s1
18 s1
17 s2
16 s2
15 s2
这是我的代码:
library(dplyr)
library(reshape2)
library (hts)
setwd("C:/Users/Desktop/r")
mydata <- read.csv("read1.csv")
mydata$newcolumn <- NA
temp1 <- mydata[order(mydata$fy_vol, decreasing = TRUE),]
nrow(temp1)
row <- nrow(temp1)
readinteger <- function()
{
n <- readline(prompt="Enter number of quant: ")
n <- as.integer(n)
if (is.na(n)){
n <- readinteger()
}
return(n)
}
q <- readinteger()
nrow(temp1)
row <- nrow(temp1)
答案 0 :(得分:1)
您的问题有太多问题。请阅读“如何制作一个重现性很好的例子”。下面的一组代码可以让你做你正在做的事情。
library(dplyr)
library(reshape2)
library (hts)
setwd("C:/Users/Desktop/r")
mydata <- read.csv("read1.csv")
col1 <- c('ram1','ram2','ram3','ram4','ram5','ram6')
col2 <- c('abc','abcd','abcde','abcdef','abcdefg','abcdefgh')
col3 <- c(15:20)
mydata <- data.frame(name = col1, school = col2, total_consumption =
col3)
mydata$newcolumn <- NA
temp1 <- mydata[order(mydata$total_consumption, decreasing = TRUE),]
nrow(temp1)
row <- nrow(temp1)
readinteger <- function()
{
n <- readline(prompt="Enter number of quant: ")
n <- as.integer(n)
if (is.na(n)){
n <- readinteger()
}
return(n)
}
q <- readinteger()
nrow(temp1)
row <- nrow(temp1)
#calculate the size of split based on if the entry is odd or even.
seg1 <- ifelse(row %% q == 0,row/2,row/2-0.5)
temp1$newcolumn[1:seg1] <- "s1"
temp1$newcolumn[seg1:row] <- "s2"