How can I change the variable(column) names in R? I couldn't do it with plyr package or any other data manipulation R package.
You can also make it like this:
df <- data.frame("1", "b", "test")
names(df) <- c("Name 1", "Name 2", "Name 3")
If you want to change the column names:
colnames(DataFrame)[colnames(DataFrame)=="Old Column Name"] <- "New Column Name"
Related
I'm looking for a way to automatically add new list elements/levels to an existing list:
my real-life use case has several thousand elements to add, so the manual example below for adding two elements is not feasible anymore,
I need a list because that's the format expected by an API I'm trying to access.
Example:
library(tidyverse)
x <- data.frame(id = c(1,2,3),
label = c("label 1", "label 2", "label 3"),
category = c("cat 1", "cat 2", "cat 3"))
x_list <- x %>%
as.list() %>%
transpose()
names <- c("name 1", "name 2")
# Expected final format/output
full_list <- list(list(name = names[1],
info = x_list),
list(name = names[2],
info = x_list))
So I'm looking for a way to create this list of lists, where I "glue together" all values from the names vector with a "copy" ot the x_list.
I'm not that familiar with lists, so struggling quite a bit. I know that the purrr package can do awesome list things, so I'm open/looking forward to a tidyverse approach, although I'm also gladly taking base R. Thanks.
Iterate over names using map or using the same arguments replace map with lapply in which case no packages are needed.
library(purrr)
result <- map(names, function(nm) list(name = nm, info = x_list))
identical(result, full_list)
## [1] TRUE
I am looking for a smarter way to create this type of name vectors in r (rmarkdown).
I have:
# 'mat' is a matrix with 10 columns
colnames(mat)<-c("Comp 1","Comp 2","Comp 3", "Comp 4", "Comp 5","Comp 6"
,"Comp 7","Comp 8", "Comp 9", "Comp 10")
Ideally I would do something with a for loop;
for i =1:10
colnames(mat)<- c("comp 'i'")
but this doesn't work. How can i do this?
Thanks' in advance!
To use loop:
mat as your dataset name
for (i in 1:length(colnames(mat))){
colnames(mat)[i] <- paste0("Comp", i, sep=" ")
}
You can also use dplyr::select() to rename colnames:
dplyr::select(mat, Comp1 = colname1, Comp2 = colname2,...)
I would like to use attributes to store variable names like Stata does with their labels: Instead of e.g. printing the variable name (to e.g. output tables), I'd rather have attribute thereof (hence I call the attribute name). But how can I access it in a loop?
dummies <- c("a", "b", "c")
attr(dummies, "names") <- c("First letter", "Second letter", "Third letter")
for (dummy in dummies) {
# do something with dummy
# e.g. accessing a variable in a dataframe
# and printing something to a table
print attr(dummies$dummy, "names") # doesn't work
print attr(dummies, "names")$dummy # doesn't work
}
As an alternative approach one can use a matrix:
dummies <- c("a", "b", "c")
names <- c("First letter", "Second letter", "Third letter")
dummies.matrix <- matrix(c(dummies, names), nrow=3)
Then I loop over dummies.matrix:
for (i in 1:nrow(dummies.matrix)) {
print(dummies.matrix[i,1]) # value
print(dummies.matrix[i,2]) # name or label
}
But that's neither convenient nor intuitive.
It looks like you have an indexing problem.
dummies <- c("a", "b", "c")
attr(dummies, "names") <- c("First letter", "Second letter", "Third letter")
for (i in seq_along(dummies)) {
print(dummies[i])
print(attr(dummies[i], "names"))
}
As a style point, be cautious about using indexes like dummy on vectors named dummies. At some point the vector and the index start to blend together, which makes it harder to interpret what the code should be doing.
I've a data frame corresponding to the sample below:
df = data.frame(subject=c("Subject A", "Subject B", "Subject C", "Subject D"),id=c(1:4))
I would like to transform this data frame to a list object that could be conveniently implemented in selectInput:
selectInput("subject", "Subject",
choices = #my_new_list )
I would like for the end-user to see the list of subjects in the selection and for the selectInput to return the corresponding numerical value (id).
If I attempt to get my list via:
df <- data.frame(lapply(df, as.character),
stringsAsFactors = FALSE)
df <- as.list(df)
The selectInput drop down menu shows all available options:
I'm only interested in listing subjects and passing the corresponding numerical values.
Use function split:
my_new_list <- split(df$id, df$subject)
my_new_list
#$`Subject A`
#[1] 1
#$`Subject B`
#[1] 2
#$`Subject C`
#[1] 3
#$`Subject D`
#[1] 4
Together with function with:
my_new_list <- with(df, split(id, subject))
For the choices argument, you can use a named list, from the doc:
If elements of the list are named then that name rather than the value
is displayed to the user
To make the named list you could try:
your_choices <- as.list(df$id)
names(your_choices) <- df$subject
And in the app:
selectInput("subject", "Subject",
choices = your_choices )
Use setNames, for example:
selectizeInput('x3', 'X3', choices = setNames(state.abb, state.name))
like in this example http://shiny.rstudio.com/gallery/option-groups-for-selectize-input.html
I need to read the ''wdbc.data' in the following data folder:
http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/
Doing this in R is easy using command read.csv but as the header is missing how can I add it? I have the information but don't know how to do this and I'd prefer do not edit the data file.
You can do the following:
Load the data:
test <- read.csv(
"http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
header=FALSE)
Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.
Add names to the different columns in the data.frame
names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")
or alternative and faster as I understand (not reloading the entire dataset):
colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")
You can also use colnames instead of names if you have data.frame or matrix
You can also solve this problem by creating an array of values and assigning that array:
newheaders <- c("a", "b", "c", ... "x")
colnames(data) <- newheaders
in case you are interested in reading some data from a .txt file and only extract few columns of that file into a new .txt file with a customized header, the following code might be useful:
# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")
# assign the name for the output file:
seqName <- "seq1_data.txt"
#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx <- civit_cam$q.x.rad.
qy <- civit_cam$q.y.rad.
qz <- civit_cam$q.z.rad.
qw <- civit_cam$q.w
# From GPS:
gpsT <- civit_gps$X.gpsTime.sec.
latitude <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude <- civit_gps$H.Ell.m.
heading <- civit_gps$Heading.deg.
pitch <- civit_gps$pitch.deg.
roll <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]
#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
c(frame_idx),
c(qx),
c(qy),
c(qz),
c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")
Of course, you should modify this sample script based on your own application.
this should work out,
kable(dt) %>%
kable_styling("striped") %>%
add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
#OR
kable(dt) %>%
kable_styling(c("striped", "bordered")) %>%
add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
add_header_above(c(" ", "Group 6" = 6))
for more you can check the link