我的数据如下:
Parameter Value Parameter Value Parameter Value
Speed 100 Time 1 Distance 260
我希望以表格格式显示所有'参数'在一列和所有'值'在另一栏
Parameter Value
Speed 100
Time 1
Distance 260
请帮助我。
提前致谢.. !!
答案 0 :(得分:0)
这是一个快速而肮脏的解决方案。我假设列数是偶数。
library(tidyverse)
library(magrittr)
library(janitor) # For making column names unique.
# Create your example dataset.
test = c('Speed', 100, 'Time', 1, 'Distance', 260) %>%
t() %>%
as.tibble() %>%
clean_names() # Make column names unique. tidyverse functions won't work otherwise.
# If you're reading your dataset into R via read_csv(), read_excel(), etc, be sure to
# run the imported tibble through clean_names().
# Create empty list to house each parameter and its value in each element.
params = list()
# Loop through the 'test' tibble, grabbing each parameter-value pair
# and throwing them in their own element of the list 'params'
for (i in 1:(ncol(test)/2)) {
# The 1st & 2nd columns are a parameter-value pair. Grab them.
params[[i]] = select(test, 1:2)
# Drop the 1st and second columns.
test = select(test, -(1:2))
}
# We want to combine the tibbles in 'params' row-wise into one big tibble.
# First, the column names must be the same for each tibble.
params = lapply(X = params, FUN = setNames, c('v1', 'v2'))
# Combine the tibbles row-wise into one big tibble.
test2 = do.call(rbind, params) %>%
set_colnames(c('Parameter', 'Value'))
# End. 'test2' is the desired output.
答案 1 :(得分:0)
@Namrata这是一种使用基本R函数的方法,不需要清除列名。
rawData <- "Parameter Value Parameter Value Parameter Value
Speed 100 Time 1 Distance 260"
# read the data and convert to a matrix of character values
# read the first row as data, not variable names
theData <- as.matrix(read.table(textConnection(rawData),header=FALSE,
stringsAsFactors=FALSE))
# transpose so required data is in second column
transposedData <- t(theData)
# calculate indexes to extract parameter names (odd) and values (even) rows
# from column 2
parmIndex <- seq(from=1,to=nrow(transposedData)-1,by=2)
valueIndex <- seq(from=2,to=nrow(transposedData),by=2)
# create 2 vectors
parameter <- transposedData[parmIndex,2]
value <- transposedData[valueIndex,2]
# convert to data frame and reset rownames
resultData <- data.frame(parameter,value=as.numeric(value),stringsAsFactors=FALSE)
rownames(resultData) <- 1:nrow(resultData)
结果输出为:
的问候,
莱恩