简体   繁体   中英

How to read one column value from CSV file in R in distinct format

How to use legend in R for the following data

ID  Gender    Age   Site      Times
1   Male      24    Facebook     10
2   Female    24    Linkedin     10
3   Male      24    Twitter      10
4   Female    24    Myspace      10
5   Male      24    Facebook     10
6   Female    24    linkedin     10
7   Male      24    Facebook     10

TO Read the CSV I've used

pd.readcsv <- read.csv(file = "snsite.csv")

To design the Pie chart I've used

pie(pd.freq[order(pd.freq,decreasing = T)],
col = c("Blue","Green","Yellow","Brown","Green"),
border = NA, main = "Site Usage")

Now to show legend at top right or top left, how to read one column(Site) value in distinct form from csv file and store it in a variable and used it in legend function?

I wasn't sure where you were getting the pd.freq object from, but assuming you are trying to get a pie chart showing per site how many times each site was visited, then this should do the trick.

# Read dataframe, I would recommend including the stringsAsFactors = FALSE argument to your read.csv command
pd.readcsv <- read.table(text = "ID  Gender    Age   Site      Times
                                  1   Male      24    Facebook     10
                                  2   Female    24    Linkedin     10
                                  3   Male      24    Twitter      10
                                  4   Female    24    Myspace      10
                                  5   Male      24    Facebook     10
                                  6   Female    24    linkedin     10
                                  7   Male      24    Facebook     10", 
                                  header = TRUE, stringsAsFactors = FALSE)

# Convert sites to lowercase for proper aggregation
pd.readcsv$Site <- sapply(pd.readcsv$Site, tolower)

# Get vector of unique site names
sites <- unique(pd.readcsv$Site)

# Create aggregate dataframe with total times per site
pd.SumSiteTimes <- aggregate(Times~Site, sum, data = pd.readcsv)

# Create vector for colors
colors <- c("Blue","Green","Yellow","Brown","Green")

# Create pie chart
pie(pd.SumSiteTimes$Times[order(pd.SumSiteTimes$Times,decreasing = T)],
    col = colors,
    border = NA, 
    main = "Site Usage")

# Add legend to the plot
legend("topright", sites, cex = .8, fill = colors)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM